Article Series

Crusade against...

May 15, 2005

There is one thought that crossed my mind: Since braces do nothing, they are basically a waste. Python recognized this and uses indentation to create blocks.

The following is a very common method in Java programs:

public void setName(String name)
{
this.name = name;
}

This method isn’t very significant for the program and it’s very unlikely to contain a defect. My editor window shows about 40 lines - after that I have to scroll down. Now a method that is insignificant and is unlikely to have a defect takes up about 10 % of the available space. Even worse I might have 9 other instance variables that need encapsulation desperatly, so I end up having a page of setter methods. If I want to see what the class really does, I have to scroll.

From that point of view, the following is better, but not much.

public void setName(String name) {
this.name = name;
}

One line saved per setter or getter. But it really doesn’t solve the problem. Why waste even three lines of code for doing almost nothing?

There is another problem with those getters and setters: clutter. If one of the setter methods does something more than just setting the instance variable it might be lost on first sight in the noise the others provide. Here is a class with a few attributes that are encapsulated by getter and setter methods. Answer as fast as possible: Which attribute(s) can’t be set and which method isn’t your normal “getter” method?

OK. Most getters and all setters were generated by Eclipse - you might be able to do better manually. The class already contains 100 lines of code that do pretty much nothing. Things get even worse when you write a documentation comment for each method (especially if it says something meaningless like “sets the size”)!

The class shrinks to about 50 lines of code, does the same thing and above all, points out the important parts of this class. It almost fits on one screen, too. A bit unfamiliar maybe - but nothing you wouldn’t be able to get used to.

Of course, if you dare to ignore general wisdom of encapsulation you can make it even clearer: