What Makes Your Code More Readable I
Shoki Ishii
Posted on November 16, 2021
Are you naming variables too casually, or writing code without caring about the feelings of reviewers?
This article is divided into several chapters with examples on how to make your code more readable, based on what I understood from the book "The Art of Readable Code".
(Boswell, D., Foucher, T. (2012). The Art of Readable Code. O'Reilly. )
Table of Contents
Packing Information into Names
1-1. Choose Specific Words
1-2. Avoid Common Names Such astmp
andval
1-3. Decide Variable Length According to the Scale of the ScopeNaming Clear Variables to Avoid Misunderstandings
2-1. Avoid to Use Ambiguous Words
2-2. Usemin
andmax
For Limits
2-3. Use Words Likeis
andhas
for boolean Variables
Why Readable Code Is Important
I think all you know the code should be readable, but have you thought about specific advantages of readable codes?
That is simply understandable and easy to review the code. Even you develop your app in your own, the reviewer may be you after a year.
Some of advantages of readable code are:
- Less time consuming to debug
- Easy to understand for reviewers
- Easy to maintain
- Easy to extend new function
Now let's see what and how you can make the code more readable.
1. Packing Information into Names
When you name a variable, you need to include information about the value. However, not just anything related to the value can be used, and there are a few tips on how to name them.
1-1. Choose Specific Words
For variables, you should choose specific words by thinking of WHAT, WHERE, sometimes HOW.
For example, the word 'get' is unclear in some cases:
❎
const getFiles = ()=>{...}
This may be understandable for a small application, but for a large application, there may be various scenes where you need to retrieve files.
So,
✅
const downloadFiles = ()=>{...};
const fetchFiles = ()=>{...};
this is more readable since readers know what the function does and returned values are easily.
Another example is
❎
let size;
✅
let areaSize;
let height;
let memoryBytes;
In this way, by having specific information in the variable name, it becomes easier to understand what the variable is for.
1-2. Avoid Common Names Such as tmp
and val
Names like tmp
and val
are not desirable because they almost do not mean anything. And reviewers need to track what it has.
For example,
❎
function averageScore(participants) {
// you need to track what it is
let val;
participants.map((participant) => {
val += participant.score;
});
return val / participants.length;
}
In the example above, val
doesn't have much information, and as a result, you have to keep track of what goes into the value of val
every time you see the code.
So using a specific name like sumScore
in this case is much better instead of using val
to tmp
:
✅
function averageScore(participants) {
// you know what it will have
let sumScore;
participants.map((participant) => {
sumScore += participant.score;
});
return sumScore / participants.length;
}
However, tmp
or val
can be used in some cases, especially for short-lived storage.
For example, in swapping,
✅
function swap(left, right) {
let tmp = left;
left = right;
right = tmp;
}
Because tmp
is only used in 3 lines in the function, this is fine.
1-3. Decide Variable Length According to the Scale of the Scope
The length of the variable should be determined according to the scope of use.
For a short scope like 5 lines, it is better to use a short name because you can check what the variable is for easily.
On the other hand, if the variable is used in a large scope, it is better to name the variable with the necessary information so that it can be understood anytime and anywhere.
❎
function eatFood() {
let amountOfFoodPersonCanEat = 0;
for (let i = 0; i < Math.floor(Math.random() * 10); i++) {
amountOfFoodPersonCanEat++;
}
console.log('Eat ' + amountOfFoodPersonCanEat + ' apples');
return
}
In the example above, amountOfFoodPersonCanEat
is shorted-lived and used one time. In that case, a shorter variable name is totally fine.
✅
function eatFood() {
let amount = 0;
for (let i = 0; i < Math.floor(Math.random() * 10); i++) {
amount ++;
}
console.log('Eat ' + amount + ' apples');
return
}
amount
is enough to understand what it has in this short scope code.
But in contrast, if you use the variable in other functions or keep using it in the function, you might want to name like amountOfFoodPersonCanEat
.
✅
let amountOfFoodPersonCanEat = 0;
function eatFood() {
for (let i = 0; i < Math.floor(Math.random() * 10); i++) {
amountOfFoodPersonCanEat++;
}
}
amountOfFoodPersonCanEat = eatFood();
.
.
.
2. Naming Clear Variables to Avoid Misunderstandings
"Will someone misinterpret this name to mean something else?" That's what you need to think when choosing a name.
2-1. Avoid to Use Ambiguous Words
filtered...
You may want to use filteredArray
or filteredObj
for filtered arrays or objects. As I mentioned before, that's fine for short-lived variables. But it may cause misunderstandings or confusion whether filteredArray
is a selected array or a deleted array. Therefore when you want to mean select out array
for a variable, it may be better to use selectedArray
. Also, removedArray
, for example, should be used to mean removed array.
❎
const filteredArray = (arr)=>{...}
✅
// These are crystal clear what the arrays are
const selectedArray = (arr)=>{...}
const removedArray = (arr)=>{...}
sliced..., spliced..., clipped... etc.
As same as filtered..., all the words could be misunderstood. So you may want to use something like slicedResultArr
and excludedArr
.
❎
// It may cause misunderstanding
const slicedArray = (arr)=>{...}
const splicedArray = (arr)=>{...}
const clippedArray = (arr)=>{...}
✅
const slicedResultArr = (arr)=>{...}
const excludedArr = (arr)=>{...}
2-2. Use min
and max
For Limits
Putting max_ or min_ in front of what is restricted is a good way to mean limits.
For example, limitNum = 5
may lead misunderstanding in some situations. It could be a minimum value, it could be a maximum value.
❎
let limitNum = 5;
if (boxSelected < limitNum) {
console.log('Not enough');
}
// or
if (boxSelected > limitNum) {
console.log('Too much');
}
In the example above, it gets harder to know that limitNum
is for a minimum value or maximum value.
So you just simply want to add min
or max
as a prefix.
✅
let minLimit = 5;
if (boxSelected < minLimit) {
console.log('Not enough');
}
let maxLimit = 5;
if (boxSelected > maxLimit) {
console.log('Too much');
}
Now, you know what the variables are and the code is simple and clear.
2-3. Use Words Like is
and has
for boolean Variables
This is one of the common rules but let me shortly explain it.
Generally, at least in English, for a question beginning with 'Is this ~~~?' and 'Do you ...?', you answer with 'Yes/No'. In this way, boolean variables should also be asked as is~
, can~
, or has~
(has
is common instead of do
).
For example, the following variables are difficult to guess if they have a boolean value.
❎
let dragOver = false;
let updatable = true;
let itemsExist = false;
Instead of these, you should use keywords to easily guess 'Yes/No'
✅
let isDragOver = false;
let canUpdate = true;
let hasItems = false;
Summary
In this article, as a first chapter, I summarized the basic tips that makes your code readable.
Packing Information into Names
1-1. Choose Specific Words
1-2. Avoid Common Names Such astmp
andval
1-3. Decide Variable Length According to the Scale of the ScopeNaming Clear Variables to Avoid Misunderstandings
2-1. Avoid to Use Ambiguous Words
2-2. Usemin
andmax
For Limits
2-3. Use Words Likeis
andhas
for boolean Variables
Be careful in naming variables so that people reading your code will easily understand what you write as you intend. As a developer, you always need to consider the possibility of misunderstanding.
I will keep writing how you can improve your code readability.
Reference:
Boswell, D., Foucher, T. (2012). The Art of Readable Code. O'Reilly.
Posted on November 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.