Friday, August 3, 2007

Mundane Problems

I have an IOC container with some beans which are listeners. I have a POJO which is in itself a listener to some events. I want to notify my beans when the POJO gets notified of some event. But, because of some intricacies in how my container works into which I won't go, I have to get the list of all beans only at the time when my POJO gets notified. Kapeesh?

Well now the problem is I can hack my way out of this by passing an instance of the IOC container to my listener which will then get a list of all the listener beans in it and notify it away to glory. But then, my POJO now needs to know about an IOC! Damn. So, I won't want to do this. This is how we solved it:

We created an interface which provides the listener beans to anyone who wants to notify them. Then injected this interface to the POJO. This is how it looked:


public interface BeanListenerProvider {

List getBeanListeners();

}

public class POJO implements SomeListener {

public POJO(BeanListenerProvider listenerProvider) {
this.listenerProvider = listenerProvider;
}

public void getNotified(SomeEvent event) {
//Do Anything...
foreach (BeanListener listener : listenerProvider.getBeanListeners()) {
listener.notify(new AnotherEvent());
}
}
//Whatever follows...
}


The good thing about this is that I now have the POJO decoupled from my container. This may be a rookie thing to do but it is easily lost when you are working on a Friday afternoon after working a lot with Eclipse code base. This led to an interesting conversation with Hakan, my teammate, about being a pragmatic coder as against being an idealist coder.

A lot of problems are mundane. Its only what you do to solve them in a clean way is going to make your work interesting. A clean code indeed gives one a kind of satisfaction which nothing can beat. OK, may be sex, but that's about it.