DEV Community

Cover image for Clean Code: From Basics to Best Practices
Md Afsar Mahmud
Md Afsar Mahmud

Posted on

Clean Code: From Basics to Best Practices

There is a common misconception among developers that adding more comments to the code means clean code.

But the philosophy of clean code is exactly the opposite: The philosophy of clean code is to minimize comments in code, and if possible, to eliminate them altogether. If your code can explain its purpose on its own, then there is no need for unnecessary comments.

So, what is Clean Code?

Clean code is code that is easy to read, easy to understand, and easy to change.

For example: your own house can be compared to a codebase.

If everything in your home is neatly organized, with things where they belong, you'll be able to find what you need whenever you want.

But if it's messy, it will be very difficult for you.

Similarly, if someone comes to your house and sees that your room is messy, they won't be able to tell where the rest room is and where the reading room is. This will make them uncomfortable too.

On the other hand, if your house is clean and tidy, anyone will appreciate your taste.

These words apply equally to code. Whether you work alone or with a whole team, your codebase must be clean, otherwise it will be a pain for everyone.

So, here I am writing about some basic topics of Clean Code, which are not discussed much, but are important for understanding Clean Code. There will be no deep or long explanation here, because there are countless books, blogs and articles on Clean Code that are more detailed and informative.

Consistent Syntax

There are many ways to do the same thing in programming, but if you can follow a single style throughout the codebase, the code becomes much more readable.

// Arrow function, no colons, no return
const multiplyByTwo = number => number * 2;

// Function, colons, return
function multiplyByThree(number) {
    return number * 3;
}
Enter fullscreen mode Exit fullscreen mode

You can see that the two functions are doing the same thing, but the syntax is different. Both are fine, but the problem arises when different syntaxes are used for the same task throughout the codebase. So, use similar syntax for similar tasks.

Consistent Case Conventions

Another rule of clean code is to follow a similar case convention in naming. There are a few common case styles in JavaScript:

// camelCase
const myName = 'John';

// PascalCase
const MyName = 'John';

// snake_case
const my_name = 'John';
Enter fullscreen mode Exit fullscreen mode

All of them are correct, and there is no problem in working. But when three different naming styles appear together in a project, the code becomes messy. One type of case convention should be chosen in a project.

  • variables → camelCase
  • components/classes → PascalCase
  • constants → UPPER_CASE

Conciseness vs Clarity

Write readable code instead of clever code.

In many cases, we try to show off our knowledge by reducing the lines of code and writing “clever” code, reducing the lines, using complex syntax. But this destroys the readability of the code. Yes, writing short code is good, but more important than that is the readability of the code, that is, that people can easily understand the code. Because the code is basically for humans, the computer understands it anyway. Martin Fowler said something wonderful about this:

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."

Example 1: Too Concise but Hard to Read

const countVowels = s => (s.match(/[aeiou]/gi) || []).length;
console.log(countVowels("hello world"));
Enter fullscreen mode Exit fullscreen mode

Yes, the code is very small. But will someone new understand it? What is regex doing? Why is it needed? It's clever, but not readable.

Example 2: More Clear (Readable)

function countVowels(s) {
  const vowelRegex = /[aeiou]/gi;
  const matches = s.match(vowelRegex) || [];
  return matches.length;
}

console.log(countVowels("hello world"));
Enter fullscreen mode Exit fullscreen mode

Here:

  • The function name is clear.
  • regex in separate variables
  • The steps are readable.
  • Understand what the code is doing at a glance

Even if it's not concise, clear and clean code is what you want.

So making the code easy to read and understand is one of the principals of Clean code. Now here are some common suggestions for maintaining it:

  • Meaningful Naming: The name of a function, variable or class should be such that it is easy to understand what it does just by looking at the name. Instead of unnecessary comments, the code should be written in such a way that it is easy to read. When read at all, it is easy to understand why it is doing what it is doing, i.e. the logic or algorithm can also be written as a comment.
  • Single Responsibility: A function will perform only one task.

Earlier I used to think that Clean Code means DRY principle so that there is no duplicate code anywhere. That's why I used to make the functions strangely complex while trying to reuse them in many places. Later after learning about Single Responsibility Principle well, I realized that if a function does only one thing, it is much simpler, readable and maintainable.

Single Source of Truth

Having a "single source of truth" means that a specific piece of data or configuration is stored in only one place in the codebase, and all other references to the code are dependent on that one place. This is important because it ensures data consistency and avoids duplication.

// Option 1: No "single source of truth"

// file 1: bankAPI.js
const accountNumber = '1234567890';

function getBalance() {
  return fetch(`https://api.bank.com/accounts/${accountNumber}/balance`)
    .then(res => res.json());
}

// file 2: balanceComponent.js
const accountNumber = '1234567890';

function displayBalance() {
  getBalance()
    .then(balanceData => {
     // display balance on the UI
    });
}
Enter fullscreen mode Exit fullscreen mode

In this option, the account number is duplicated in two places. This will be difficult to maintain. If the account number needs to be changed, it will have to be changed in both places.

// Option 2: "Single source of truth"

// file 1: bankAPI.js
const accountNumber = '1234567890';

function getBalance() {
  return fetch(`https://api.bank.com/accounts/${accountNumber}/balance`)
    .then(res => res.json());
}

export { getBalance, accountNumber };

// file 2: balanceComponent.js
import { getBalance } from './bankAPI';

function displayBalance() {
  getBalance()
    .then(balanceData => {
       // display balance on the UI
    });
}
Enter fullscreen mode Exit fullscreen mode

In this option, the account number is kept in one place and other modules use it. This ensures that there is a single source of truth for the data and no duplication.

If you need to change your account number, you only need to change it in one place, and it will be updated automatically in all other places.

Wrapping Up

By reading this article, you have learned some basic things that can help you start your clean code journey. There are many more guidelines that you can explore to practice better.

One thing to keep in mind when coding:

"It is more important to reduce the effort of maintenance than it is to reduce the effort of implementation." (Max Kanat-Alexander)

Reducing maintenance time should be given more importance than reducing code implementation time. We should always think long-term.

Top comments (2)

Collapse
 
md-afsar-mahmud profile image
Md Afsar Mahmud

For anyone interested in diving deeper into clean code, here are some excellent resources that expand on the concepts discussed in this post:

● Clean Code: A Practical Approach – Medium
medium.com/clarityai-engineering/c...
● How to Write Clean Code – freeCodeCamp
freecodecamp.org/news/how-to-write...
● Clean Code Summary Notes
gist.github.com/wojteklu/73c6914cc...
● Common Clean Code Mistakes – LinkedIn Article
linkedin.com/pulse/clean-code-mist...
● Clean Code & Software Principles (SOLID, YAGNI, KISS, DRY)
medium.com/@burakatestepe/clean-co...

Collapse
 
a-k-0047 profile image
ak0047

Thank you for sharing this article!
I'll keep it in mind.