MuTasim

What's Clean Code?

⌛ 3 min read

I recently completed a course on "Clean Code," an essential aspect of software development. I would like to share my insights with you. Let's dive deeper and understand what clean code is and how we should write it. I will explain some concepts and provide examples from the course I took. Enjoy!

What's Clean Code?

So, what exactly is clean code? Let's examine this example:

transactions.js
function processTransactions(transactions) {
  if (transactions && transactions.length > 0) {
    for (const transaction of transactions) {
      if (transaction.type === 'PAYMENT') {
        if (transaction.status === 'OPEN') {
          if (transaction.method === 'CREDIT_CARD') {
            processCreditCardPayment(transaction);
          } else if (transaction.method === 'PAYPAL') {
            processPayPalPayment(transaction);
          } else if (transaction.method === 'PLAN') {
            processPlanPayment(transaction);
          }
        } else {
          console.log('Invalid transaction type!');
        }
      } 
    } 
  }
}

Do you think this is clean code? Probably not. Many of you may agree that it's not clean. It's hard to understand due to the deeply nested control structure, making it look messy. Let's consider another example:

validate.py
max = create('Max', 31)

Is this clean code? Although it's just one line of code and you may think it's creating a user with a name and age, let's take a look at the entire code:

validate.py
def create(m, n):
    if m == 'Max':
        return lambda v: v < n
    elif m == 'Min':
        return lambda v: v > n

max = create('Max', 31)

print(max(15))
print(max(31))

Take a moment to understand what this code is doing. It's a bit complicated, right? This code doesn't create a user; instead, it creates other functions. The code defines a function that generates lambda functions for checking whether a given value is less than or greater than a specified threshold. In the provided example, it creates a function for checking if a value is less than 31 ('Max'), assigns it to the variable max, and then prints the results of applying this function to the values 15 and 31. This is not clean code because it is confusing and takes a while to understand.

To make it clean, we can rewrite the example:

validate.py
def create_validator(mode, number):
    if mode == 'Max':
        return lambda value: value < number
    elif mode == 'Min':
        return lambda value: value > number

is_below_max = create_validator('Max', 31)

print(is_below_max(15))
print(is_below_max(31))

By changing the names, we make the code easier to understand.

There isn't a single right way to make code clean; let's explore another approach using classes:

validate.py
class ValidatableNumber:
    def __init__(self, number):
        self.number = number
    
    def is_bigger_than(self, other_number):
        return other_number < self.number

    def is_smaller_than(self, other_number):
        return other_number > self.number

input_number = ValidatableNumber(31)

print(input_number.is_bigger_than(15))
print(input_number.is_smaller_than(32))

This is an easy and clean way to represent the same example.

So, what is clean code?

  • It should be readable and meaningful.
  • It should reduce cognitive load.
  • It should be concise and "to the point."
  • It should avoid unintuitive names, complex nesting, and large code blocks.
  • It should follow common best practices and patterns.
  • And, of course, it should be enjoyable to write and maintain the code.

Clean code is easy to understand; dirty code is not. As a developer, you are the author of your code, and you need to write it so that it's easy to read and understand. In my next blog post, I will discuss some techniques and rules that can help you write clean code.

Happy coding! ❤️