...

/

Writing Code with Readability in Mind

Writing Code with Readability in Mind

Learn how to increase the readability of code using comments and documentation.

The importance of readable code

Code that we write will not just be executed by the computer. It will also be read both by ourselves and others. Therefore, it’s essential that we write code that’s as easy to read and understand as possible.

There are some simple rules we can follow that will assist in achieving readable code.

Using comments and documentation wisely

When creating code, you understand what you’re doing and why you’re doing it. But when you come back to the code a couple of months later, it isn’t always as clear what these thoughts were and why you wrote things the way you did. Commenting on tricky lines of code is a great way to document your thoughts for both your future self and others that will read your code.

But comments can also make the code less readable. Never comment on things that are obvious—these are things that any programmer, including yourself, will understand.

You should use comments when you look at a line of code and understand that a reader who sees this line will need to stop and think before understanding what it does.

Commenting on functions and methods is often a good idea. These comments will usually come right before the function or method or as the first thing inside it. What you should use depends on what language you’re using, as well as the conventions used by programmers of that language.

In the following code, we can see an example of this for a JavaScript function:

Press + to interact
/**
* Insert table headings
* @param {HTMLTableElement} table - The target HTML table
* @param {Array} headers - Array of cell header names
*/
function insertTableHeadings(table, headers) {
const thead = table.createTHead();
const row = thead.insertRow();
for (const header of headers) {
const th = document.createElement("th");
const text = document.createTextNode(header);
th.appendChild(text);
row.appendChild(th);
}
}

The following is what we can infer from the code above:

  • The first text line in this comment describes the overall responsibility of this function. Then, using the predefined @param name, the meaning of the two parameters are documented.
  • Within the curly brackets, the data type that’s expected is defined. This is especially important if the language we’re using is dynamically typed. A dynamically typed language will accept any type we assign to a variable, rather than using only the type we specify. JavaScript is dynamically typed, so this will assist any programmers using this function.
  • After that comes the name of the parameter (table and headers).
  • Then, after a dash, we’ll document what this parameter is used for.

Many editors used by programmers can use this documentation if formatted correctly. The format we can see here ...