Enough already lets write some events! Make stuff happen!

Whoa, slow down there. We need to look back at why events are useful first.  Remember that first time you really “got” events?  That same day you got hit by lightning and managed to power your laptop without a battery or plug for hours?  Yeah, it was like that for me too.  Lets look at one of those o-so-fun examples of what makes events so great: The Space Balloon Attackers.

Lets say you were programming a game, one of your own original ideas that is in no way whatsoever a copy of space invaders with balloons. As you begin to code your not space invaders game, you realize that events make things super easy for you to send messages between your objects.  It allows you to separate different pieces of the functionality into some logical objects and yet still talk to that main class.  Your space balloons will notify the game class when then come onto the screen, and the ThumbtackCannon class can notify the balloons when it's fired a Thumbtack.   Finally the balloon could notify the game class that it has been popped. 

So this really makes things pretty streamlined and we can already see how events can be of help to us, but that's not the whole picture.  Events try to sneak away from a problem that all code can potentially suffer from. Spaghetti coupling.  By using listeners and dispatchers, events have a way of letting objects state what is important to them right up front.  Basically they only need to "register to be notified later."  This can be nice because it organizes the references we must keep track of from one object to another rather that having to remember that we need to call the method popReallyBigBalloonAndShowPowerUp() on the balloon class when a tack hits it.

So perhaps as you start to code, you sketch out the connections each class will have with each other. Early on with just a few objects things look something like this:

(Note: only pseudo-UML here for simplicity)


Well that looks pretty neat.  We’ve got some of our basic classes and events and we seem to be following good OOP principles.

But this is where we cue up some elevator music... ( time passes by ).... And later, when we’ve really dug into the code our classes might start to look more like this:



Oops what do we do now? Does the above diagram look familiar?  Perhaps conjuring images of pasta?  Yes, indeed I like spaghetti too --  I like most all kinds of pasta actually; but it’s best eaten with some pesto or marinara sauce, not splattered all over our code right? 

Well who hasn’t regurgitated some spaghetti code at one time or another?  I know I have.  But that’s besides the point (and a little disgusting).  Rather than talk about code upchuck, how about we see what we could do to help solve our spaghetti dilemma.