BrainsToBytes

Writing good variable names

There are only two hard things in Computer Science: cache invalidation and naming things
_Phil Karlton

Despite being one of the easiest ways of improving the quality of code, writing good variable names is perhaps the most overlooked skill in a developer's toolbox.  Sharpening your naming chops is a sure way of improving your code's readability regardless of the project's complexity.

There are lots of advice on how to improve your naming skills. I collected the tips I've found the most useful for crafting effective, concise and readable variable names.

Provide valuable information

In software, a thing's name has a single goal: to clarify what it does and why it exists. Variables that give you this information save you from having to decipher how they fit in the code.

  • Etch meaning in every single name. The name should accurately describe the entity it represents.
// None of these names provide useful information
int d;
String n;
boolean sg;

// These names clearly state what they represent
int distanceInLightYears;
String starName;
boolean isSupergiant;
  • Embed meaningful domain knowledge into the name.  It must be clear what entity from the domain a variable represents. A name like bitFlag is not as meaningful as isUserLoggedIn or isEngineReady. Whenever possible, favor names that have clear relations with your problem's domain.

  • Use your software knowledge. Factory and List are words with a special meaning for software developers. Words for programming concepts let you express complex ideas in a few words that are easily understandable by fellow programmers. In fact, programming lingo offers you heaps of information compression for free, so feel free to use it.

Trim the bloat

Good names strike a balance between being informative and concise. In other words, you want names to be instructive and at the same time to be lean and readable.

  • Don't put type information on the name. Modern statically typed languages made names like stringName obsolete. Even when working with dynamically typed languages this approach just bloats the name.
// Instead of writing names like these ones
public class Dog{
  private int intAgeInYears;
  private String stringName;
  private boolean boolHasOwner;
}

// Keep type information out of variable names
public class Dog{
  private int ageInYears;
  private String name;
  private boolean hasOwner;
}
  • Keep useless context out. Don't put into a variable name information like the class, package or module it belongs to.
public class Shape{
    private int shapeWidth;
    private int shapeHeight;
    private String shapeName;
}

//I already know it's a shape, there is no need to repeat it on every variable
public class Shape{
    private int Width;
    private int Height;
    private String Name;
}
  • (Controversial?) Don't prefix member variables or interfaces. In some places it's common to prefix member variables with the letter m or interfaces with the letter I. Because modern editing tools provide this information, I ditch this type of prefix.
public interface IProduct{...}

//Skip the I, it doesn't add any meaningful distinction next to the word 'interface'
public interface Product{...}

Don't let the name get in the way of your tools

  • Use easy to pronounce names. We, humans, have amazing language processing capabilities. Unpronounceable abbreviations are harder to 'process' than normal words. With this in mind, strive to keep your names brain-friendly.
//Avoid using unpronounceable abbreviations in an attempt to shorten a name
private String cchdPgHdr
private String cachedPageHeader;
  • Use searchable names. Making your names searchable help you save lots of time. Using magic numbers or very short names like 'se' make finding the variable you need more difficult. Whenever possible, avoid names that return dozens of results when searching for them.

Enforce consistency across all names

  • Use antonyms for variables that represent the opposite. This is another way of using your brain language skills to your advantage. In this case, the word-to-concept mapping makes the relation between variables obvious.
// These variable pairs have an obvious relation to each other
private String oldCityMotto;
private String newCityMotto;

private int firstDigit;
private int lastDigit;


// Avoid word pairs that represent opposite concepts indirectly, strive to choose the obvious antonym
private Element first;
private Element tails;
  • Choose a word per concept and stick to it. Our brains love consistency. Not having to juggle with several words for a single concept saves a lot of mental effort.
private ElementController valveController;
...
private ElementController switchController;
...
private ElementController turbineController;
...
//Avoid using different words for representing the same concept
private ElementController speakerManager;
  • It's ok to name loop indexes i,j,k...* Most index variables need no extra explanation. There are several techniques to improve a loop's readability. However, using index or nth as index rarely improves anything.

Good names are about empathy and agreement

Good variable names come from the same place all good programming practices stem from: empathy. Recognizing your code as a means of communicating with your fellow developers is the first step to achieve great quality in programming. With this purpose in mind, transform every variable name you write into a clear message to everyone who reads your code.

Lastly, naming conventions are your friend. Creating conventions everyone in the team agree with is an easy way to avoid headaches. You don't need to start from scratch, as most programming languages have naming guidelines you can reference anytime. Just to list a couple of them:

What to do next:

  • Share this article with friends and colleagues. Thank you for helping me reach people who might find this information useful.
  • You can find more information about this topic on chapter 2 of Clean Code and chapter 11 of Code Complete. This and other very helpful books are in the recommended reading list.
  • Send me an email with questions, comments or suggestions (it's in the About Me page). Come on, don't be shy!
Author image
Budapest, Hungary
Hey there, I'm Juan. A programmer currently living in Budapest. I believe in well-engineered solutions, clean code and sharing knowledge. Thanks for reading, I hope you find my articles useful!