Wednesday, January 03, 2007

Indirect programming

Yesterday during a debugging session a colleague and I stumbled over a terrific example of what I have called 'indirect programming' elsewhere:

  private void start(String organizerId) {
IBreakpointOrganizer organizer = getOrganizer(organizerId);
IPropertyChangeListener listener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
}
};
organizer.addPropertyChangeListener(listener);
organizer.removePropertyChangeListener(listener);
}
Why in the world would someone first add and then immediately remove a listener, and above all a listener with an empty implementation?? Here's why (taken from what happens to be one internal implementation class of IBreakpointOrganizer):
  public void addPropertyChangeListener(IPropertyChangeListener listener) {
getOrganizer().addPropertyChangeListener(listener);
}

[...]
protected IBreakpointOrganizerDelegate getOrganizer() {
if (fDelegate == null) {
try {
fDelegate = (IBreakpointOrganizerDelegate)
fElement.createExecutableExtension(ATTR_CLASS);
} catch (CoreException e) {
DebugUIPlugin.log(e);
}
}
return fDelegate;
}
Adding a listener has the (undocumented) side-effect of initializing the internals of the organizer. The implementation of the method above makes thus use of a) an implementation detail it shouldn't know; and b) a behaviour that is clearly a side-effect of an entirely different functionality. One can only hope that not, at some future time, a source code cleanup will just clean away that 'useless' add/remove a no-op piece of code ...

1 comment:

Thiago Arrais said...

... and pure functional programming has the antidote for that: no side effects.