Part 4 of 6 · 2 min read
The trap
Do not call overridable methods in a constructor.
Template Method relies on inheritance, which brings the risks of Level 1, module 4. EJ Item 19 adds a specific rule: a constructor must not call a method that a subclass can override. The reason is that the parent constructor runs before the subclass constructor. An overridden method can run before the subclass has set up its fields.
class Super {
Super() { init(); }
void init() { }
}
class Sub extends Super {
private final String name = String.valueOf("ready");
private String seen;
@Override void init() { seen = String.valueOf(name); }
}
After new Sub(), seen holds the text "null", not "ready". The parent's constructor called init() before name was assigned, so the override saw a field that was still empty. This happens even though name is final. (If name were a plain constant text, the compiler would copy its value in, and hide the bug. The trap is real in all other cases.)
EJ's advice for classes meant to be extended: document which methods can be overridden and what they do, never call overridable methods from constructors, and if a class is not designed for inheritance, forbid it with final or a private constructor. The template method in section 2 follows this: it is a normal method, not a constructor, and it is final.
A last point. A template method that has too many steps becomes hard to subclass, because the subclass author must understand every step. Keep the number of abstract steps small. GoF notes that minimizing the operations that must be overridden is an important design goal.
Common mistake
Calling a step from the constructor of the abstract class. The subclass's fields may not exist yet.
Check yourself:
1. Why was seen "null"?
2. Why is the template method in section 2 safe?
3. What does EJ say to do with a class that was not designed for inheritance?