DEV Community

Eric Damtoft for DealerOn Dev

Posted on

A Simple Rule for Better Variable Naming

Variable naming is simultaneously one of the most trivial and complex aspects of writing code. Variables names are largely irrelevant to the computer running your code after it's been compiled, but they can make a world of difference for a human who has to read and maintain code.

There's a few general rules of thumb:

  • Keep names as short and simple as possible while still being descriptive
  • Follow naming conventions of the system you're coding in

But in addition, here's a more concrete one I've found to be a helpful guideline:

Make booleans affirmative

Think about the following line of code:

var disabled = true;

There's nothing inherently unreadable about that line of code, but when it comes time to use it, we probably are thinking about whether something is enabled and have to invert it. As complexity builds up, this mental flipping can take a toll on comprehensibility of your code.

if (!disabled) {
  doStuff();
}

Instead, we can rename disabled to enabled and reason about it without needing to mentally invert it.

if (enabled) {
  doStuff();
}

This way, we're using true to represent an "on" state and false to represent an "off" state which is considerably more natural to read. Although this seems trivial, it can have a big impact on overall readability of code. If you're not convinced yet, think back to the worst multiple choice test you've ever taken. The question probably looked something like this:

Which of the following is not true?

a) two plus two is not three
b) two minus two is not one
c) two divided by two is not one
d) two times two is not five

If you're like me, your internal dialog just went something like "So if it's not not true then that means... wait..." as you try to flip the logic in your head.

By writing it as an affirmative question, it becomes much easier to comprehend:

Which of the following is true?

a) two plus two is three
b) two minus two is one
c) two divided by two is one
d) two times two is five

Although these two representations are logically equivalent, it's much more human friendly. Just flipping a few logical statements in your head takes a noticeable toll even when the underlying logic is simple. When the underlying logic becomes complex, it can make it completely unintelligible.

Alt Text

Although there's no rule without exceptions, checking to make sure you're not flipping your bits is always a good thing to have in the back of your mind. It's often a simple refactor and can make for much more straightforward code.

Top comments (0)