Saturday, May 23, 2009

Fragile Base Class Problem - Not Quite

I have never encountered the fragile base class problem when programming, but I encountered something remarkably close when I was writing code for our comp sci group project today.

I was extending the DefaultMutableTreeNode class. It has two remove methods, remove(int childIndex) and remove(MutableTreeNode node) for removing children from this node. I was overriding these two methods as I was keeping a separate map of the nodes, my remove(int childIndex) method found what node was at childIndex, and them called remove(thatNode).

Now, my remove(MutableTreeNode node) method would remove the node from my map, and then call the superclass' remove method. The superclass' remove method must have been (confirmed by looking at the java souce code) calling remove(int childIndex), which I had overriden, so my version got called, which called my other remove method, which called the superclasses remove method - loop until the stack overflowed. Was pretty easy to see that this was happening from the stack trace.

Now, the fragile base class problem is when changed a base class causes a derived class to break, where this is slightly different in that the implementation of the base class caused the derived class to break. Now, if the DefaultMutableTreeNode class were changed so that the remove(int childIndex) called the remove(MutableTreeNode node), then I would suffer the fragile base class problem.

Oh the joys of programming.

No comments:

Post a Comment