Naming Things

Take pride in your code.

It is hard to overestimate the importance of choosing good names for source code elements in software development. Much has been written on this topic, and it is often a source of great debate. “What makes a name good, or better than another?” “What about my favorite cryptic notation that I’ve been using since last century?” “Everybody should always use my favorite prefixes/suffixes everywhere!” The topic of naming things can frequently degrade into such discussions, but here we will discuss some principles that should inform your decisions when naming things that are generally accepted today by professional software developers.

The first principle of Naming Things is to be consistent within your team or project. It doesn’t matter what your personal preference might be, it’s more important that the code everybody is sharing uses consistent names. There are other guidelines and recommendations below, but none of them trump this one.

Names are one of the most powerful tools you have for communicating your code’s intent to those who read your code (including yourself, in the future). It’s critically important to choose meaningful names. It’s also important that the names you choose make sense not just to you, but to others involved on the project – your team. One way to dramatically improve the consistency and quality of your names is to pair with another developer on your team, since whatever names the two of you come up with that make sense to both of you are now very likely to be accepted and understood by the other members of the whole team. Having two developers involved in creating new code constructs also makes it more likely the code will follow the project’s naming conventions, assuming these aren’t already being enforced by a tool (like StyleCop or JustCode orReSharper).

Names should describe why a programming element exists, what its purpose is. If a name is so short that a comment is necessary to state its actual purpose, then it is too short. For instance, in Clean Code, Tim Ottinger notes that:

int d; // elapsed time in days

is an example of a poor name. Instead, consider names like these:

int elapsedTimeInDays;
int daysSinceCreation;

Note here that the units are included in the variable name. Consider the .NET Framework’sThread.Sleep method, which takes an Int32. There is no ambiguity about the units of this value, since it is named millisecondsTimeout.

Avoid mixing opposites – be consistent (don’t use begin/end in one place, start/finish in another, etc.)

Avoid numbers (e.g. item1, item2, item3)

Make the names of methods and classes as long as necessary to accurately describe what they do. If the resulting name is too long, it’s a good indicator (or code smell) that the construct in question is probably trying to do too much, and should be broken up into several more cohesive parts.