Clean Code – Intention Revealing Names
One of the fundamentals of writing clean code is to use a proper naming when it comes to declare variables or methods. It’s important to ensure readability because as a developer grows in its career you deal with a lot of projects and at a certain point you need to update certain components but if you don’t remember and neither you understand the code it will require much more time to finish your work.
Besides that, when you work collaboratively it will be hard for other developers to read your code if you don’t have readability, or it will be hard for you if someone passes a code that is not properly named.
That’s why in this article you will learn more about how to intentionally use revealing names.
Example 1
int d; // elapsed time in days
This variable doesn’t passed immediately the reason it exists.
Options feasible for it are:
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
This are much more intentionally driven names that immediately pass the idea for which they are used for.
Example 2
Can you tell the purpose of this code?
The problem isn’t the simplicity of the code but the implicity of the code (to coin a phrase): the degree to which the context is not explicit in the code itself
Clean Code – Page 49
A clean code can’t require that we implicitly know what the methods and variables represent. To write a better code image that we are playing mine sweeper game. The list of cells is called “theList”, we can rename to “gameBoard”. Each cell on the board is represented by a simple array.
The zeroth subscript is the location of a status value and that a status value of 4 means “flagged.”
In that case we could have this option:
The code is now much more understandable. We can even create a simple class for cells instead of using the int[] and can include an intention-revealing function “isFlagged”, for example:
Conclusion
With those changes you and others developers can understand the purpose of the code, making easier to extend (if necessary) and even to test.