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:
- Things that can be done in an initialization block should be done there instead of a constructor.
- 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) { this.name = name == null || name.length()== 0 ? "anonymous" : name; } public Person(String name, int salary) { this(name); 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.