Readable code, one name at a time

Any fool can write code a computer can understand, but it takes a good programmer to write code a human can understand — Martin Fowler

Table of Contents

TL;DR

Naming is particularly hard if we want our code to be its own documentation. That is, that each variable, method, class, and module is named in a clear and meaningful manner. Why? Because code is meant to be changed and that’s easier to do and achieve if the code is understandable to others and ourselves at a point in time in which we are no longer immersed in that business domain. Here are some suggestions on how to name the elements of our code.

Pronounceable names

Given that code is one of the main ways programmers communicate with each other the use of good names should make the code easy to read and understand. Hence, always use pronounceable names, it will make easier to talk about about code.

Communicate intent

Names should reveal intent, that is, it should be clear what they stands for. Whenever we need to read the code to understand a name then clearly that name has failed to communicate its intent.

Parts of speech

Names should be as abstract as the class/variable they stand for. Classes and variables are nouns. Methods are verbs.

The name of a class should be a noun or a noun phrase, such as Account or MessageParser.

Variables, since they often hold instances of classes, should be nouns.

In Ruby, booleans should be named as questions, like empty?, any?.

Enumerables tend to be states or object descriptors, so they often could be adjectives.

Avoid generic names

Avoid generic names such as manager, processor, data, and info. That kind of naming usually implies that one has not fully comprehended what a variable, method or class is doing.

The scope/name length rule

For variables, the name length has to be proportional to its scope. The longer the scope of the variable, the longer its name. On the other hand, variables in a rather small scope should have smaller names; down to even a single letter.

Regarding functions and classes, the longer the scope, the shorter the name. Public methods should have short names simply because they are going to be called from several places and so they should be convenient to use.

Private methods, should have long names, it kind of works for self documenting the code. Since private methods tend to be very detailed their name should document exactly what it does. Since its private is not expected to be called from many places and so a longer name shouldn’t be a problem.

Avoid disinformation

A name should say what it means and mean what it says. Hence, if the “meaning” of a function (what it does) changes then its name should change too. As long as we have a sound test suite, refactoring that should be fairly simple. Sticking to the previous naming suggestions should help us prevent disinformation.