Monday, August 02, 2004

Messaging with generics

Talking to my programming pairmate, Gregor Hohpe, we discussed a Java project using messaging that distinguished messages by type rather than by id or topic. A drawback is that with JDK1.4 you need reflection or extra coding to make it work nicely. Generics in JDK5 take care of this:

public interface Receiver<E extends Event> { void receive(final E event); } public interface Channel<E extends Event> extends Receiver<E> { void subscribe(final Receiver<E> receiver); void unsubscribe(final Receiver<E> receiver); }

Here, receivers and channels are typed by event. By making events into a hierarchy—consider the advantages and disadvantages of the Exception hierarchy—, ipso facto receivers and channels mirror that hierarchy. (In this fragment channels are multiplexed receivers, one of many choices.)

One could also type receivers by channel:

public interface Receiver<E extends Event, C extends Channel<E>> { void receive(final E event); }

But this seems too tightly coupled.

No comments: