5 Tips to Master the Art of Clean Code
Tags: productivity, codequality, career, programming
Published: 2021-08-08 05:46:04

> Good programmers write boring code. Great programmers write really boring code

When I came across this quote on the internet, sometime in the past year, it introduced me to the concept of clean code. 

# What is **Clean Code** exactly?

In simple terms **Clean Code** refers to a codebase that is easy to read and understand. Some salient features of **Clean Code** are:

- Reduces **cognitive load** of the reader
- Contains intuitively named **variables** and **functions**
- Follows the **best practices** for coding

# Why use **Clean Code** when my code works even without it?

Glad you asked. **Clean Code** is not about writing code that works, it is about writing code that is easy to read and maintain in the long term. As you can see from this graph, the cost of maintaining a **Dirty Code** base drastically increases over time, whereas in the case of **Clean Code**, it remains fairly constant.

![Graph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4b4tdpmoww5p79a04oi.png)

**Clean Code** is not the **shortest** or the **smartest looking**, but it is the **elegant** code, understanding which takes _minimal effort_.

**Programming** is an **art** as much as it is a **science**. Here are a few tips to help you write **Clean Code**.

# 1. Intuitive Variable Names

Quite evidently nobody does all the computation mentally to check what a variable stores.

**Example 1**

```js
const x = n.filter(e => e > 0);
```

**Example 2**

```js
const positiveElements = numbers.filter(num => num > 0);
```

As you can see the second example is far easier to understand than the first one.

In the case of **booleans** the variable name should be a question that can be answered with _yes_ or _no_, such as

```js
const isValid = false;
const hasAuthorization = true;
```

# 2. Self-Explanatory functions

There are two things to keep in mind while writing functions or methods:

1. Follow the **Single Responsibility Principle (SRP)**
2. Function names should be actions words (verbs)

**Single Responsibility Principle (SRP)** states that a function should do only one specific task. An example of this would be a function that _sends data to the server_ **should not** _validate the data_.

```js
const validate = (data) => {
 // ...
}

const sendData= (data) => {
 // ...
}

const submit = (data) => {
  if (!validate(data)){
    return;
  }
  sendData(data)
}
```

There are two other _good to follow_ principles:

1. Function body should not contain more than 2 levels of nesting
2. A function should take a maximum of 3 arguments 

# 3. Group Similar Functions Together

We now come across the concept of **Cohesion**. **Cohesion** is a measure of the _degree_ to which the elements of the module are functionally related.

Related functions should be grouped together in a class, helping us keep our code compartmentalized

```py
class IOHelper:
  @staticmethod
  def read_data(file_name: string) -> None:
    pass

  @staticmethod
  def write_data(file_name: string, data: Any) -> None:
    pass
```

Here we find that the `IOHelper` class only groups together functions for **io** operations, without having any utility of its own.

# 4. Minimize The Number Of Comments

This might sound **counterintuitive** for some beginners, but hear it out. The code you write should be **self-explanatory**, anyone viewing your code should not have to rely on comments to understand what it does.

There are a few rare cases where you might need comments in case there is some unintuitive code without a workaround.

```js
// using setTimeout to avoid race-condition
setTimeout(fn, 0)
```

# 5. Code Formatting

The codebase should always follow a strict set of **formatting** rules. It is also a good idea to use a formatter like [black](https://pypi.org/project/black/) or [prettier](https://prettier.io/) to automate the formatting.

The **Project Structure** should be decided before the commencement of the project and everyone working on it should be aware of it and agree to abide by it, as the **Project Structure** is context-dependent and everyone likes a specific structure over another.

The variables and function naming convention should also be specified beforehand (`isValid` or `hasVality`, etc.) and language-specific cases should be kept in mind (eg: **snake case** in **python** and **camel case** in **JS/TS**).

```py
snake_case_variable = "value"
```

```js
camelCaseVariable = "value"
```

# Conclusion

As mentioned earlier as well, **Clean Code** is not the **shortest** code, but it is the easiest to understand. Following these principles would help you become a **better coder** not by improving your _coding skills_ but by improving the _soft skills_ required for coding as it will teach you how to explain your code to _non-technical people_.

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

# Thanks for reading

Want to work together? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [GitHub](https://github.com/ruppysuppy)

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for weekly new tidbits on [Dev](https://dev.to/ruppysuppy)

**FAQ**

These are a few commonly asked questions I get. So, I hope this **FAQ** section solves your issues.

1. **I am a beginner, how should I learn Front-End Web Dev?**
    First get the fundamentals of **HTML**, **CSS**, **JS** down; Learn any _front-end framework/library_ (**React**, **Vue**, **Angular**); Then keep making **Projects** or make **Open Source Contributions** to attain mastery.

    **Relevant Article Links**
        1. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)
        2. [Get Started With Open Source](https://dev.to/ruppysuppy/zero-to-hero-get-started-with-open-source-10b7)

2. **Would you mentor me?**
    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

**Connect to me on**

-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose-429a601a0)
-   [Portfolio](https://tapajyoti-bose.vercel.app)
-   [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)
-   [GitHub](https://github.com/ruppysuppy)
-   [Instagram](https://www.instagram.com/tapajyotib/)