Thursday, June 4, 2009

Naming things

People who know me know that I'm rather a fanatic about naming things.

One of the fundamental lessons that I think I've learned over 30 years of writing software is that names matter. Spend a lot of time thinking about how you name variables, how you name methods and functions, how you name classes, how you name tables and columns, etc. Names are frustratingly hard to change later, but if chosen well they can make all the difference in writing clear and understandable code.

There are lots of good naming conventions out there. Go read some of them and try to stick to them.

I've found that, if names are well chosen, you will see a greatly reduced need for comments, because the code itself will be self-evident and natural to read:


if (shelvesToInventory.contains(shelf))
shelf.inventoryContents(reportFile);
else
shelvesOmitted++;


The flip side of the coin is that a poorly chosen name can simply demolish the understanding of code, and make it practically impossible to read. Often, when I find such code, I simply have to rewrite it on the spot, because otherwise I'm just constantly fighting with the code and I feel like my brain is thrashing.

Double-negatives in code often do this to me:


if (! o.isMissingParts() )
o.setIncomplete(false);
...
if (! o.isIncomplete())
process(o);


emerges from my editor as the much more legible:


o.checkForMissingParts();
if (o.isComplete())
process(o);


Anyway, the point of this post is that I nearly lost my lunch when I read this the other day:


public class BaseDependencyHandler
extends CustomDependencyHandler
{
...
}


Luckily there were no small children or church-goers around to be offended by my reaction...

No comments:

Post a Comment