Saturday, October 20, 2007

Never invoke a public method from another public method

In the previous post we saw how subclassing from a class not designed for inheritance, can be dangerous. Using composition instead of inheritance would have solved the problem. But what was the crux of the problem? Could such a trap have been avoided? Could AbstractCollection have been implemented so that such a situation would not have arisen in the first place?

The real problem was the class AbstractCollection which was not designed properly for inheritance. It is a non-final class with a public method addAll(Collection c) which invokes another non-final public method add(Object o).

How should AbstractCollection have implemented add(Object o) and addAll(Collection c) to prevent such a problem?

I do not know if this problem has been fixed in OpenJDK. They may have not been able to do so to maintain backwards compatibility. You can check out the sources from their website.

In the next post we will discuss an idiom for preventing such a situation. 

Discuss this post in the learning forum.



Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

No comments: