Sending messages in your application

I got a question from a friend the other day that went something like this:
I have an application that has n modules, and I need to communicate between them.  I have been using some messaging stuff for a while now, and as my application has gotten more complicated, it has become messy.  How are you doing this?

Communication between modules in any application is always tricky, and can always get messy.  Think of it this way.  What if I wanted to send a text message to somebody.  Only, instead of sending it to somebody, I had to hope the right person / people were expecting my message, and would act appropriately.  And, conversely, i would also hope people who were not supposed to be listening were not, and didn’t do anything when I sent the message.  See Twitter and it’s incredible reliability.

So how do you solve this problem?  Well, the quickest way is to download a messaging framework like Courier (thanks Brad!).  Now you can send messages where ever you want!  Although I am not a fan of the messaging idea, I really like everything in my application to be as defined as possible.  I have never really felt comfortable sending a message “SelectedItem” with the item selected attached to it as an object.  I just don’t like it when I have to count on my subscriber to convert my object to the right thing (boxing and unboxing concerns aside).

My preferred way to solve this problem is to created an object who's sole responsibility is to keep track of the selected item.  Then, using my favorite dependency injection framework, I would register the ItemSelector and anything that needed a reference to my item selection object could get at it.  Here’s what the interface would look like:

This defines all the pieces we need for the selection, now for the implementation of the interface:

Now, any part of my code that might need to know about selection change, just needs to have a reference to the instance of ItemSelector (or, if you are using dependency injection, would just need to be injected with the IItemSelector interface).  Of course, the standard cautions apply to subscribing and then UNSUBSCRIBING from events.  But this should work fine, and can be expanded to fit the needs of your complexity.

Share this post!

0 comments:

Post a Comment