views:

192

answers:

7

Had a code smell moment and couldn't decided if its OK for a class to be Observable and also an Observer, so thought I'd post here.

class ObservableAndObserver extends Observable implements Observer {

 // Class is ofcourse registering and receving notifcations on different events
 // effectly actving as a middle man. 

 // Is this a pattern in itself?  'middleman-pattern' ??

}

Thoughts? Breaking SRP?

+1  A: 

I don't see any reason why not. A concrete example would be useful though. Even better would be real code that you have already implemented, that we could critique.

anon
+3  A: 

It is technically ok, but you should check that you aren't simply re-transmitting received notifications. If this class is observing class1, and then being observed by class2, try having that class observe class1.

Marius
Thanks. It's not a re-transmit in this scenario.
JamesC
A: 

While I agree with Neil, I could see it being a code smell because the class could be doing too much.

Austin Salonen
A: 

as long the object observe events of other objects and it is observed by other objects it is ok. But if the object observe itself probably there is something really weird.

Maybe some code will help to understand if the design pattern was used in a weird way.

dfa
A: 

This is one way many event based systems implement filters. The other would, in Java, have an inner class for one of the roles, but that's more common if the filter has multiple observers with different roles. So if you think that it might end up with different roles, you may want it to have an accessor for the role you've currently in mind getObserver() { return this; }, but that is probably a YAGNI and can be added later.

Pete Kirkham
+1  A: 

It's ok :-). If class subscribes to other class event and can raise its own events it's ok. Sure you can do it wrong but the concept of class to look for some other class and be observable is ok.

Yaroslav Yakovlev
A: 

it's evil. b observes a and notifies c.

so there is a piece of code that says a.setValue(...) and something in c happens.

now think this: that piece of code instead should have said: a.setValue(...); c.doSomething(...);

of course that piece of code must now know about a and c but at least there is no magic. everything is under the sun. information hiding in oo is for the code in setValue(...) no in the observer/observable pattern multiplied by 2.

Cheers, L.

lalala