tags:

views:

352

answers:

2

Was chatting to a colleague about the design of Javas libraries. I mentioned I'd always found it funny that the AWT/Swing classes called that essentially provide an Observable interface on a UI widget were actually called "listeners".

Whereupon he floored me by pointing out that there would have been a name clash with java.util.Observer and java.util.Observable, which have been around since JDK 1.0. I'd never heard of them before.

There are no usages listed in the JavaDocs and google/googlecode don't come up with much, so does anyone know if they are used somewhere in the JDK? They don't seem to have received any Generic love, so presumably they're not "popular". Has anyone found them useful?

+1  A: 

They are not used, because their design is flawed: they are not type safe. You can attach any object that implements Observer to any Observable, which can result in subtle bugs down the line.

Wrapping them inside a type safe interface is about the same amount of work as implementing the pattern from scratch, so I guess the latter is preferred in most cases.

This is one of the things which are flawed in Java 1.0 due to suboptimal design choices made under time pressure (others include the Java 1.0 Collection API and java.util.Date), but due to the nature of public APIs can never anymore be removed (only deprecated).

Péter Török
@Péter Török: You can only attach an object that implements the *Observer* interface to an *Observable*, this is perfectly normal. I hope that by wrapping them inside a type safe interface you're not thinking about using generics, because it ain't working for observer/observable due to type erasure (well, it works, but only for trivially simple case, where the basic Observable works too). But granted, it's so easy to implement from a scratch using a COWAL that there's not much point in using these old 1.0 remnants.
Webinator
@WizardOfOdds I know this. I edited the code, hopefully it is clearer now.
Péter Török
@WizardOfOdds: The use of generics for an observable/observer is that the observer usually must have access to the observable as cast to its relevant type in this context. Since the JDK's pattern implementation does not provide generics, it raises ClassCast issues easily.
Christopher Oezbek
+2  A: 

Observer and Observable are still used in a lot of Eclipse wizard code for detecting when the stuff in input boxes changes, so the wizard itself can be updated. I've had to work with some of this stuff, changing it for our own needs.. :)

Chris Dennett