This blog post summarizes the book “Clean Code” written by Robert Martin on how to write a readable and maintainable code. We’ll use JavaScript to illustrate the rules and best practices of the book.
Clean code is a book written by the American software engineer and instructor Robert Martin, published in 2008. The book is abprogramming best practices gathered from years of experience in the industry in order to write good and clean code that can be easily maintainable in the long term. Even though the examples that the author uses in his book are in Java, the book's concepts remain relevant for Javascript and programming in general.
Robert Cecil Martin is an American software engineer, instructor, and author. Robert Martin is best known for being the founder of the agile manifesto and developing many software design principles. Robert Martin is also the author of the well-known book “Clean Code” discussed in this blog post.
Put simply, a clean code is a code that is easy to read and easy to change. It is a code that has been taken care of and where its author has taken the time to keep it simple and ordered.
But why should we bother about writing a clean code? Why can’t we just stick with a messy code if it’s well functioning? Well, there are many reasons for this, but the most important ones are:
Below is a summary of some of the recommended rules to write a clean and understandable code. We’ll illustrate those recommendations by the JavaScript programming language. The more detailed and exhaustive list of the recommended practices to write a clean code can be found in the book.
Because names are everywhere in a software, it’s very important to choose well defined names in order to exactly convey our intention. Here are some principles recommended from the book :
//Bad naming
const d = new Date();
//Good naming
const currentDate = new Date();
Robert Martin states that the most important rule for functions is that they should be small. The longer the function is, the harder it becomes to clearly understand what it is doing and therefore refactoring or improving the function becomes harder. As a rule of thumb, Robert Martin states that functions should hardly be longer than 20 lines. Here are some recommended rules to have clean and understandable functions :
setSomething
should only do the “set” action and nothing more. If a function is doing multiple actions, this function becomes hard to test and hard to refactor or improve whenever there is a need.//Bad
function notifyUsers(users) {
users.forEach(user => {
const userRecord = database.lookup(user);
if (userRecord.isVerified()) {
notify(user);
}
});
}
// Good
function notifyVerifiedUsers(users) {
users.filter(isUserVerified).forEach(notify);
}
function isUserVerified(user) {
const userRecord = database.lookup(user);
return userRecord.isVerified();
}
Comments should be avoided. The book's author recommends always looking for ways to express ourselves in code instead of using comments.
Comments are bad because what they express is often far away from the code they describe for the simple reason that code changes and evolves and comments are not always maintained.
There are, however, some cases where comments can be useful :
Code formatting is about having some set of rules that governs the format of our code. Code formatting is important because it makes the developer’s code easier to read and understand. As we previously mentioned, a developer’s job is not only about shipping a functioning code. Writing readable and maintainable code is equally important. It is better if formatting is handled by some automated tool.
Below are some of the rules recommended by the author for a nice code format:
// Good code
const handleClose = () => {
setOpen(false);
};
const handleSubmit = (e) => {
e.preventDefault();
handleClose();
};
Thrown errors mean that the runtime has identified some errors in our code and lets the developer know by stopping the function execution. Here are some recommended rules from the book on how to successfully handle errors :
Instead of handling a potential error in the following way
const setProperty = (obj, value, property) => {
obj[property] = value;
if (!value) {
return "Value not found";
}
}
We should instead, handle the potential error with an exception
const setProperty = (obj, value, property) => {
if (!value) {
throw new Error('Value not found');
}
obj[property] = value;
}
function divideTwoNumbers(x, y) {
if (y === 0) {
throw "Can't divide by 0";
}
return x / y;
}
try {
const result = divideTwoNumbers(5, 0);
} catch (error) {
console.log(error);
}
Software testing is an essential activity in the software engineering pipeline, and it has the purpose of finding potential defects or miss behaviors in the system under test to correct these by debugging. If we don’t have any tests or if our tests are insufficient, we have no idea that some piece of shipped code isn’t breaking anything in the already existing codebase.
There’s no excuse not to write tests. In JavaScript, there are plenty of automation testing tools that one can use. I personally use Jest for my JavaScript projects.
Below is what the author recommends to have a clean code test:
// Not recommended because we are testing multiple concepts
import assert from "assert";
describe("MomentJS", () => {
it("handles date boundaries", () => {
let date;
date = new MomentJS("1/1/2015");
date.addDays(30);
assert.equal("1/31/2015", date);
date = new MomentJS("2/1/2016");
date.addDays(28);
assert.equal("02/29/2016", date);
date = new MomentJS("2/1/2015");
date.addDays(28);
assert.equal("03/01/2015", date);
});
});
// Good code
import assert from "assert";
describe("MomentJS", () => {
it("handles 30-day months", () => {
const date = new MomentJS("1/1/2015");
date.addDays(30);
assert.equal("1/31/2015", date);
});
it("handles leap year", () => {
const date = new MomentJS("2/1/2016");
date.addDays(28);
assert.equal("02/29/2016", date);
});
it("handles non-leap year", () => {
const date = new MomentJS("2/1/2015");
date.addDays(28);
assert.equal("03/01/2015", date);
});
});
What if there were 4 rules that we needed to follow in order to create simple designed programs ? This is what Kent Beck's four rules of Simple Design are about. In a nutshell, according to Kent, a software design is simple if it follows those four rules ranked from the rule with the highest priority to the one with the lowest priority :
Because a given software code is an artifact that will live long after it is first created and will certainly be edited and improved in its lifetime, a developer's job shouldn’t be just about writing a functioning code. Developers must write a clean code that is easy to maintain and easy to read and follow. To reach that objective, developers must follow the habits and practises gained from years of experience of the most experienced developers in the field. That’s what the clean code rules we talked about in this blog post are all about.
If this post was helpful to you in any way, please don't hesitate to share it. You can also follow my Twitter account or visit my website if you would like to see more content related to web programming.