Monday, July 30, 2012

Silly method calls

I know my millions of readers are hanging on the edges of their seats waiting for the third part of the driving primer, but I encountered something at work today that I just have to comment on.

I was looking through some code and found something like the following. (I can't give the real code since that belongs to the company.)

typeComboBoxEnable(true);

Further down is the definition of the method being called

private void typeComboBoxEnable(boolean e) {
    typeComboBox.enable(e);
}


In other words, the unnamed engineer who wrote this code chose to use three lines to write a method PLUS a line to call the method when the method consisted of a single line in the first place. Why not just put typeComboBox.enable(true) in place of the method call? There is no good reason, really. Since the person who wrote the code is no longer with the company, I can't even ask him what the heck he was thinking; I can only guess. So, of course, that's exactly what I'm going to do. :-)

This particular software was originally written in C++ and was translated to Java by C++ programmers who had taught themselves Java. One of the principles by which Java programmers tend to work is to write "self-documenting" code. This means that instead of writing a bunch of complex code in the middle of a method in order to accomplish something, put that complex code in a method and give the method a name that describes what the code is supposed to do. Some people who are making a transition to using Java interpret this as meaning that you should always do this, even if there is only one line of code to go in the method. My guess is that this is exactly what the unnamed engineer was thinking.

Look at the code in the example above. Is typeComboBoxEnable(true) more clear than typeComboBox.enable(true)? I would argue that it is not. For one thing, they contain exactly the same description of what is being done; there is no benefit to documentation to call the method instead, and by doing it that way, more code had to be written. This is a poor design and should be avoided.

No comments:

Post a Comment

To prevent spam, comments made more than two weeks after the original post date will not appear until I've had a chance to approve them.