Search code examples
c#.netdependenciesdecouplingloose-coupling

Do events really make code decoupled?


So I am trying to use events to decouple code that I have and here is my problem:

class WorldHandler
{
    public void Notify(object sender, EventArgs e)
    {
        if (e is CameraMovedEventArgs)
        {
            // handle event
        }

        if (e is MapLoaded)
        {
            // handle event
        }
    }
}

WorldHandler class listens to different subsystems of my application. Doesn't that mean that WorldHandler is still coupled with other subsystems? Wouldn't it be the same to access those subsystems inside this class directly?

If it's hard to understand what I am asking I will add additional information to my post.

I did research on this problem and I still found this confusing, because different people have very different opinions on how to decouple your code with events.


Solution

  • Yes your code is still coupled, you not only have a direct reference to the class (when you hook up the event handler) but you also have a reference to the assembly containing the class being watched.

    You can minimise the coupling by using an interface on the watched class and only accessing it via the items exposed on the interface. Ideally this interface should be in a third "more common" assembly which both the watcher and watchee reference. You can also minimise or eliminate the event coupling by using something like the EventAggregator in Prism.

    Coupling in itself is not bad, it simply makes it more difficult (or expensive) to swap out implementations and replace them - without proper decoupling there is considerably more work and more risk of bugs. Your application may not need proper decoupling - it depends on what you intend to do with it.