I learned a long time ago that there are essentially three different kinds of relationship between two classes. They are, in order of increasing tightness:
- Uses, in which I care only about your public API;
- Creates, in which I also need to know your class;
- Inherits/extends, in which I can also see some of your workings and I become part of you.
Don’t do that last one. Ever.
Many of the GoF patterns help move code up this list, from tight towards loose coupling. Except TemplateMethod, which not only encourages inheritance, it also creates a circular dependency by having the superclass only “work” in the presence of extensions. Bad.
Don’t inherit code. Bad.
Good ol’ http://c2.com/cgi/wiki?CompositionInsteadOfInheritance ! :)
Thank you, I’m not the only one thinking Inheritance is bad in 99% of its uses.
My rule of programming.
Don’t say “don’t” ever.
Inheritance has its place and is incredibly useful. So is composition. Horses for courses.
Template Method has a compositional form: replace abstract class with concrete class using an interface. Problem solved and Template Method rehabilitated. :)
Isn’t that the Strategy pattern?