Wednesday, June 10, 2009

Calling non-private methods from constructors

Every time I join a new project there is usually a discussion about the Coding Guidelines. Usually it includes stupid guidelines, like "use underscore prefix with the fields" or "end constants with "CN".
In extreme stupid cases the guidelines require surrounding methods with "try-catch" blocks, while catch does something like "log.error(exception); return null;" and later it becomes impossible to understand from the log what actually has happened.

Usually I insist on adding the following guideline: "Never call methods that can be overridden by a subclass from the constructor." It means that if you decide to call a method from the constructor, it should be either private, or static, or final. It's also possible to declare the whole class final.

Why?

Run the following example and see what happens.
public class Base {

public static class A {

public A() {
printHello();     // calling method from constructor
}

protected void printHello() {
System.out.println("Hello!");
}
}

public static class B extends A {

private String helloWorld = "Hello world!";

public B() {

}

// override printHello
protected void printHello() {
System.out.println(helloWorld.length());    // Null pointer exception will be thrown here.
}
}

public static void main(String[] args) {
B b = new B();
}

}


Recommended Reading

1. How Would You Move Mount Fuji? Microsoft's Cult of the Puzzle - How the World's Smartest Company Selects the Most Creative Thinkers
2. User Interface Design for Programmers
3. Code Complete: A Practical Handbook of Software Construction

No comments: