Wednesday, May 25, 2011

Constructors v Init blocks

With time code begins to bloat and the procrastination regarding re-factoring and code clean-up makes a new comer to the project feel like groping her way out of a maze.

One tiny contributor to such lack of maintenance is how some classes have multiple non-trivial constructors and modifications in one constructor of a class is forgotten to be made in other constructors.  Two ways to avoid this:
  1. Things that can be done in an initialization block should be done there instead of a constructor. 
  2. If the language supports it, constructor chaining should be utilized to avoid duplication of  code.
By constructor chaining, I mean something like the following (Java):
class Person {
    private final String name;
    private int salary;

    public Person(String name) { = name == null || name.length()== 0 ? "anonymous" : name;
    public Person(String name, int salary) {
         this.salary = salary;
If you are like me in that you want to declare as many fields final as possible but a field has a non-trivial initialization step, that can also go in an init block.