Clean Code: Meaningful Names (Chapter 2)

Jonny Caley
2 min readApr 14, 2020

This is the first in a series of articles detailing key points I found whilst reading Clean Code. This article focuses on Chapter 2: Meaningful Names.

Disclosure: The points outlined throughout this series do not summarise the contents of the book. They simply outline some key points I found that programmers like myself (2–3 years of programming experience) may find as useful learning material. I would advise you to read the book first, and then refer to this series to reinforce your learning such as I did.

With that said, let’s begin…

Utilising a class to reveal intent

Classes can be used to reveal the intent of code and make it more explicit.

Situation: Let’s say you are playing minesweeper, and you want to get all the cells that contain a mine. Each cell on the board is represented by a simple IntArray. We further know that the zeroth value in a cell’s array is the status value and that the status value of 4 means that cell is a mine. Here is the following function to get all the mines:

Now this code is ok, but there is still some ambiguity in the if statement. The condition cell[0] == 4 opens up the function to potential questions from developers: Why is it that the first Int in the cell determines the mine state? Why does that state have to be 4 for it to be a mine?

The problem is that this information is at the wrong level of abstraction, making it harder for developers to understand what’s going on.

Solution: We can write a simple class called Cell instead of using an IntArray to clear this up. This class can then include an intention revealing function (called isMine) to hide the magic numbers. The results are as follows:

With these changes, it is no longer difficult to understand what’s going on. The ambiguity of the if statement is now hidden within the Cell class, making the function logic easier to understand.

--

--