Three principles for naming things

Written by on

There's a saying most of us developers should be familiar with:

There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

Naming is hard.

Over time, I've realized you can make it easier on yourself. If you're a beginner, you can follow these three general principles.

It's never ok to use a variable named "p"

Storage space is cheap. You don't need to worry about using short variable names. It's not a valid excuse.

Stop being lazy. If your variable is holding a project, call it project - don't call it "p". You should be able to come back to your code six months later, look at that line, and immediately know that "p" is a project.

So you say you have an amazing memory? It's still not an excuse. Some poor guy will have to read your code in the future and he'll think "p" stands for prick.

It's never ok to use abbreviations

Writing code is all about asking the question, "If I leave this project and come back in six months, will I know what this means?"

It's a constant battle. Another way to win this battle is to stop using abbreviations. Have you ever tried to read someone else's writing where they use a lot of abbreviations? Isn't it hard? Why would you want to use abbreviations for the next poor guy working on your project?

The exception is reserved for conventions.

For example, the HTML standard uses "src" quite a bit which everyone knows to mean source. A common abbreviation in JavaScript is "evt" which obviously stands for event (if you're familiar with JavaScript).

These are conventions which most developers have agreed upon through code review and years of experience. Don't try to invent conventions simply because you're lazy.

Don't feel bad about using variables with long names

Don't worry about long variable names. Usually, the more descriptive you are, the better.

Here's an example. Suppose you query for archived projects and need to store them in a variable. Use "archived_projects" as a name for the variable.

If you broke the rules above, you might try "ap" or "arch_proj" or "a_projects". It might seem obvious to you now, but how will you know what these mean six months from now? It's not worth it.

These principles might seem obvious to you if you've been a developer for years, but it's something we should all keep in mind as we review code and teach others. These principles aren't obvious to beginners.

If you think back to when you first started, you weren't thinking about maintaining your code. You just wanted to get the damn thing working. However, you reach a point where you need to make it easier for yourself and others.

At the very least, if you learn how to be descriptive with names, you'll help everyone around you.