Method Overriding vs Method Calling – Understanding the Commitment

apicompositioninheritanceobject-oriented

From : http://www.artima.com/lejava/articles/designprinciples4.html

Erich Gamma: I still think it's true even after ten years. Inheritance is a cool way to change behavior. But we know that it's brittle, because the subclass can easily make assumptions about the context in which a method it overrides is getting called. There's a tight coupling between the base class and the subclass, because of the implicit context in which the subclass code I plug in will be called. Composition has a nicer property. The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called.

I don't understand what he means. Could anyone please explain it?

Best Answer

A commitment is something that reduces your future options. Publishing a method implies that users will call it, therefore you can't remove this method without breaking compatibility. If you'd kept it private, they couldn't (directly) call it, and you could some day refactor it away without problems. Therefore, publishing a method is a stronger commitment than not publishing it. Publishing an overridable method is an even stronger commitment. Your users can call it, and they can create new classes where the method doesn't do what you think it does!

For instance, if you publish a clean-up method, you can ensure that resources are properly deallocated as long as users remember to call this method as the last thing they do. But if the method is overridable, someone might override it in a subclass and not call super. As a result, a third user might use that class and cause a resource leak even though they dutifully called cleanup() at the end! This means that you can no longer guarantee the semantics of your code, which is a very bad thing.

Essentially, you can no longer rely on any code running in user-overridable methods, because some middleman might override it away. This means that you have to implement your clean-up routine entirely in private methods, with no help from the user. Therefore it's usually a good idea to publish only final elements unless they are explicitly intended for overriding by API users.

Related Topic