Thursday, November 27, 2008

Why not to prefix local variables, method arguments or fields

As I was reading the section "Local variables, method arguments, and fields: Which is which?" in Four harmful Java idioms, and how to fix them I thought I might try using a convention like the one proposed in the article to improve readability. (The convention was essentially to prefix the names of fields and method arguments.)

The article stated what at first looked like good arguments for improving readability by using prefixing. But after thinking about it some more and finally looking at some of my own code to see the effect, I found that the arguments were not applicable for me. Here's why:

For refactoring reasons I'm a big fan of using getter and setter methods. Even within the class declaring the field. As such, prefixing a field would in my case be more or less useless as they are only referenced in the getter and setter methods.

The need to prefix method arguments to not confuse them with local variables arises, in my opinion, when the method is too long or when the arguments are too many. Both are well defined smells and should be refactored.

No comments:

Post a Comment