Design – Does “notification center” pattern encourage good or bad program design

Architecturedesignsingletontesting

Sometimes I come across these message-hub-style APIs, for example the Cocoa NSNotificationCenter: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

Usually these APIs provide a global access point on which you subscribe to or broadcast messages/events. I'm thinking this is a problem because it encourages a flat and unstructured program architecture, where dependencies are not explicit in the API, but hidden in the source code. You are not forced to think about object ownership and hierarchies, but can rather make any object in your program result in any code anywhere being called. But maybe this is a good thing?

Does this pattern generally encourage good or bad program design, and why so? Does it make the code harder or easier to test?

Forgive me if this question is too vague or broad. I'm trying to wrap my head around the potential consequences of extensive use of an API like this, and the different ways you could use it.

Edit: I guess my biggest issue with this pattern is that the API "lies" about dependencies and object couplings, and can be illustrated with this example:

myObj = new Foo();
myOtherObj = new Bar();
print myOtherObj.someValue; // prints 0
myObj.doSomething();
print myOtherObj.someValue; // prints 1, unexpectedly, because I never indicated that these objects had anything to do with each other

Best Answer

I wouldn't go as far as saying it encourages bad programming. But it can easily be misused.

Well what is the actual idea?
The source of the notification only makes its notification. It doesn't make an assumption about the existence of potential observers or anything. An observer registers for notifications it is designed to handle. The observer doesn't make any assumptions about how many potential sources there are for the notifications it may handle.

This is a way to achieve dependency injection, without ever having sources know observers or observers know sources. However for the whole system to work, you need to wire up the right observers for the right notifications, and this system is even vulnerable to typos, because it cannot be compile time checked.

The biggest danger of course is, that someone will use this to make tons of objects globally available for 1-1 calls.

Related Topic