Books Computer Science Software Engineering

Clean Code – Chapter 2: Naming Conventions

This is the second post of my analysis on Clean Code: A Handbook of Agile Software Craftsmanship called Meaningful Names. We are going to analyze what the correct naming conventions are and how should we name variables, classes or functions in terms of clean code.

If you haven’t already, please check the previous article here. You can also buy the whole book here

There is no need to say, but we name everything that is not part of the languages keywords. We name variables, functions, classes, files, modules, packages and so on. And if we do something that much, we better do that right.

Use Intention-Revealing Names

Well, duh! But how? There is a single key takeaway here:

If a name requires a comment, then the name does not reveal its intent.

Let’s analyze a use case.

public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
    if (x[0] == 4)
        list1.add(x);
return list1; 
}

The code is just 7 lines and has a single loop and condition, but it is barely understandable. Why? Because we don’t know,

  • What is theList and what kind of things does it include?
  • Why is the first element of the array important?
  • What is the significance of the value 4 ?
  • What can I do with the returned list1 ?

Suppose we were trying to build a mine sweeper game, with pre-defined constants

final byte STATUS_VALUE = 0;
final byte FLAGGED = 4;

From now on, we can understand why 0 and 4 are important values. We keep flag status at first item and use 4 as the positive flag value.

Try to read it again.

public List<int[]> getFlaggedCells() {
List<int[]> flaggedCells = new ArrayList<int[]>(); 
for (int[] cell : gameBoard)
    if (cell[STATUS_VALUE] == FLAGGED) 
        flaggedCells.add(cell);
return flaggedCells; 
}

We didn’t change anything about control flow or logic of our code. We didn’t reduce complexity either, but the code became much more explicit.

To add a final touch, we can create a class Cell and define a function isFlagged()

public List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard)
    if (cell.isFlagged()) 
        flaggedCells.add(cell);
return flaggedCells; 
}

Avoid Disinformation

You must avoid leaving false clues that can obscure the meaning of the code. For example, ps is a well known command line tool in unix world.

If you had a pseudoprime number that you want to save and decide to use ps as variable name, that would be a poor choice.

Another thing is, that you shouldn’t add misinforming suffices to variables. Do not call something accountList if it does not actually implement the List

Do not use names that differ in small ways. FreeTheMallocBlogdatabaseControllerForStrings and FreeTheMallocBlogDatabaseHandlerForStrings are not distinct at all.

Make Meaningful Distinctions

Do not try to cheat compiler while naming. For example, let’s say you have a class and want to name it class but you obviously can not. Do not try to cheat to compiler by using klass as your variable name.

Do not just add numbers to variable names to make distinction. eg. a , a1, a2 ...

Use Pronounceable Names

Because it is easier to discuss while speaking and easier to remember as well. It may be a great abbreviation of a incredibly long name like:

dbmscfso = "DataBaseManagementSystemControllerForStringsOnly"

But it is easier to forget and harder to discuss through a healthy conversation.

Use Searchable Names

Try to use unique words while naming. It would be extremely hard to find a variable named a because it can appear anywhere.

This is not that big of a deal anymore, most IDE’s and Text Editors have advanced search features with match whole words only, but still a good habit.

However, for constants, it might come handy. In my opinion, you should always name save your constants as variables.

Never use magic-numbers directly like

int day = 1

instead, use;

int MONDAY = 1;
int day = MONDAY;

Avoid Encodings

Unlike old times, when we worked with languages Fortran and Basic, where variable name lengths were limited and type systems were weak, had to use encodings to distinguish complex stuff. But this is not necessary anymore and increases readability complexity.

Avoid Mental Mapping

int a = 4;
int b = 2;
int c;

c = a; 
a = b;
b = c;

This is a simple 2 value swap, imagine this was a longer code piece. It may come handy to use c as the temporary variable, because you can map that simply in your mind. However, another reader (including future you), might have hard time understanding this. Instead, you could rename c as temp .

Class Names

A Class name should be a noun, avoid using verbs or words like Processor , Controller etc.

Method Names

Methods should have a verb or verb phrase names like publishPost , deleteUser , or store. For accessors, mutators etc. always use the standard convention:

getName() , setName() or isMike()

Don’t Be Cute

Cute, clever names are only cute and clever to your sense of humour. The person reading this doesn’t have to be as clever as you. AtomicBomb might imply you that it destroys everything, but just use DeleteEverything . Choose clarity over entertainment, if you want to make jokes so bad, sprinkle some in your comment.

Pick One Word per Concept

If you are describing the action of collecting a piece of data from a remote location, pick one word and stick to it. Either use get, fetch , or retrieve, but never interchangeably.

A consistent lexicon is a great boon to the programmers who must use your code.

Use Solution Domain Names

The readers of your code will be CS people, so use that. Appropriate CS terms can explain a lot. Just compare the name pizzaLine where you could use pizzaQueue or pizzaStack depending on your behavior. Use it.

Use Problem Domain Names

If there is a problem based word for it, use it. Think about a program you are developing for mathematicians. Do not call the side accrossTheRightAngle , call it hypotenuse.

Add Meaningful Context

You can add prefixes to give context to a variable. firstName might not be clear enough, but patientFirstName tells a lot more.

Don’t Add Gratuitous Context

Too broad context is not meaningful at all. Take FreeTheMalloc, if I were to prefix FTM to every variable, it would make no impact regarding understandability.

Final Words

Do not be afraid of refactoring the code. There are amazing tools for developers. Git, TextEditors, IDE’s, command line tools and so on. You might surprise your colleagues, but if you follow these rules, they will only thank you for it.

Of course, always double check when messing with shared code.

The third Chapter will be about Functions, start reading now!

1 thought on “Clean Code – Chapter 2: Naming Conventions”

Leave a Reply

Your email address will not be published. Required fields are marked *