Prefixes for local fields, arguments and fields
Friday, August 1. 2008
John O'Hanley wrote a Java World article about Four harmful Java idioms, and how to fix them. In this article he discusses some standard Java idioms that should be changed.
I do not want to comment on the others but on his suggestion to add different prefixes to variables:
- f for fields
- a for arguments
- no prefix for local variables
His example that should prove in his opinion that this is better readable is:
public boolean equals (Object aOther)
{
if (! (aOther instanceof Range)) return false;
Range other = (Range) aOther;
return fStart.equals(other.fStart) && fEnd.equals(other.fEnd);
}Well I couldn't disagree more with him:
- I don't consider this more readable. You have to remove the prefixes from your mind, before you can read it.
- There is IDE syntax highlighting support in every known Java IDE. However this may make sense for Java developers that use VI as their primary IDE. But I doubt that they are handling large Java projects.
aOther could also be a local variable starting with a. In this case it might not be obvious, but I have read variables like `aDog` several times, when the local variables refers to some unspecific instance of a Dog type. The prefix is not obvious for people that are not familiar with the convention.
- Variable prefixes are breaking support for refactoring. E.g. let Eclipse generate getters and setters for fStart and you'll get getFStart() and setFStart(...). Then you'll fix the getters and setters and decide to rename the field. Normally eclipse can also automatically rename getters and setters. Not in this case.
- John believes that the use of the this qualifier to mark fields is not enough. Sure, there is still the possibility to not know what is a local variable and what is an argument. His reason was that it's easy to differ between this two types of variables in short methods, but hard in longer methods. Well, John - ever heard of test driven development? An essential part is to have short methods with significant names. That makes code much more readable than long methods with obscure prefixes for variables. And with regards to adding the this qualifier to fields... Eclipse can add it automatically each time you save a file. Very handy.
Trackbacks
Trackback specific URI for this entry
No Trackbacks
Comments