Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
martynaspikunas Avatar asked Feb 22 '14 08:02

martynaspikunas


2 Answers

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.

like image 140
slugster Avatar answered Oct 04 '22 15:10

slugster


Using events to react to things happening is decoupling. Decoupling with events isn't bad, I recommend you do it. The purpose of events is that some class says "I have done this" or "I'm about to do this", and other classes can react to the event if desirable. The class that sent the event can't normally know if any other classes reacted to it, unless you tell it of course.

like image 22
Spans Avatar answered Oct 04 '22 17:10

Spans