DEV Community

Cover image for What Makes Your Code More Readable I
Sho-ki
Sho-ki

Posted on

What Makes Your Code More Readable I

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

  1. Packing Information into Names
    1-1. Choose Specific Words
    1-2. Avoid Common Names Such as tmp and val
    1-3. Decide Variable Length According to the Scale of the Scope

  2. Naming Clear Variables to Avoid Misunderstandings
    2-1. Avoid to Use Ambiguous Words
    2-2. Use min and max For Limits
    2-3. Use Words Like is and has 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:

  1. Less time consuming to debug
  2. Easy to understand for reviewers
  3. Easy to maintain
  4. Easy to extend new function

Now let's see what and how you can make the code more readable.

1. Packing Information into Names

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 = ()=>{...}
Enter fullscreen mode Exit fullscreen mode

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 = ()=>{...};
Enter fullscreen mode Exit fullscreen mode

this is more readable since readers know what the function does and returned values are easily.

Another example is


let size; 
Enter fullscreen mode Exit fullscreen mode

let areaSize;
let height;
let memoryBytes;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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
  }

Enter fullscreen mode Exit fullscreen mode

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
  }
Enter fullscreen mode Exit fullscreen mode

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();
.
.
.
Enter fullscreen mode Exit fullscreen mode

2. Naming Clear Variables to Avoid Misunderstandings

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)=>{...}
Enter fullscreen mode Exit fullscreen mode

// These are crystal clear what the arrays are
const selectedArray = (arr)=>{...}
const removedArray = (arr)=>{...}
Enter fullscreen mode Exit fullscreen mode

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)=>{...}
Enter fullscreen mode Exit fullscreen mode

const slicedResultArr = (arr)=>{...}
const excludedArr = (arr)=>{...}
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Instead of these, you should use keywords to easily guess 'Yes/No'


let isDragOver = false;
let canUpdate = true;
let hasItems = false;
Enter fullscreen mode Exit fullscreen mode

Summary

In this article, as a first chapter, I summarized the basic tips that makes your code readable.

  1. Packing Information into Names
    1-1. Choose Specific Words
    1-2. Avoid Common Names Such as tmp and val
    1-3. Decide Variable Length According to the Scale of the Scope

  2. Naming Clear Variables to Avoid Misunderstandings
    2-1. Avoid to Use Ambiguous Words
    2-2. Use min and max For Limits
    2-3. Use Words Like is and has 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.

Discussion (4)

Collapse
sschneiderihrepvs profile image
sschneider-ihre-pvs • Edited on
function swap(left, right) {
  [right, left] = [left, right]
}
Enter fullscreen mode Exit fullscreen mode

;)

Collapse
shoki profile image
Sho-ki Author

You're right, that is easier to recognize it is a swap! Thank you so much for sharing this!

Collapse
imiahazel profile image
Imia Hazel

Excellent article. You have gripped it elegantly. It has just rebooted my coding toolbox.

Collapse
shoki profile image
Sho-ki Author

Thank you for the comment. Hope this was helpful to you!