Tidying Up: Key Insights from "Clean Code"
Tags: beginners, programming, agile, python
Published: 2023-09-22 23:09:52

## Introduction

Let's not mess around. Change is the only constant in the realm of software development. And in this ever-changing world, it's crucial to have a solid foundation of principles and practices to guide our decisions. ESPECIALLY when it comes to ouputting code. "Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin (affectionately referred to as "Uncle Bob" throughout the book) provides just that—thoughtful and insightful perspective into the fact that producing code that is not only functional, but also MAINTAINABLE is an ever-present challenge.

Published in 2008, Uncle Bob's "Clean Code" quickly became one of the quintessential classics among programmers and developers alike, offering universal principles and guidelines that can be applied to any codebase. While some of the later examples tend to get a bit heavy (a product of the time, perhaps?), the core principles throughout the book remain true today, and once I internalised the words, I've found myself coming back again and again to the following core principles when I sit down to build something. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rasjwjqxo6r7cqgrgzlx.png)

Some of this might sound basic, but it's surprising how the deeper you go trying to make something work, the less you can pay attention to those fundamentals of programming that won't look like ancient hieroglyphics to your coworkers. Here's what I took from the book, in massively condensed format!:

> _Clean code always looks like it was written by someone who cares._ - Michael Feathers

The following post aims to share key insights I gathered from reading this almost-timeless classic.

## Meaningful Function Names

The first fundamental principle discussed in the book is the importance of choosing descriptive and meaningful names for all variables, functions and classes. Uncle Bob advocates heavily that code should be "off the cuff self-explanatory", and well-chose names can serve as effective documentation in their own right.

```
# Bad variable name example
x = 42

# Good variable name example
totalScore = 42
```

The idea is that, according to Uncle Bob, when someone reads your code, they should be able to follow the logic effortlessly, understand its purpose, and grasp the intent of the programmer. By adhering to descriptive variable and function names, following the Single Responsibility Principle (SRP) (Which will be extrapolated on further down in this article!), and reducing complexity, you can ensure your code tells a clear and compelling narrative.

## Small Functions (or, the Single Responsibility Principle)

The second principle the book explores is the important of keeping functions small, concise and focused on doing one single thing well. The SRP, as outlined in Clean Code, states that a function or class should only have ONE reason to change. This principle aims to promote modularisation and maintainability by ensuring that each component of your codebase is responsible for a single, well-defined task. Following SRP results in cleaner, more maintainable code that is easier to test and extend.

The following function ignores the SRP:

```
def process_data():
    # This function is vague and doesn't indicate its purpose.
    # It does multiple things, making it hard to understand.
    data = fetch_data_from_database()
    sanitized_data = sanitize_data(data)
    result = compute_result(sanitized_data)
```
The following function abides by the SRP, resulting in smaller chunks of much clearer, managable functions. Each function's purpose is evident from its name, and makes the code more readable, maintainable and easier to understand:

```
def fetch_data_from_database():
    # This function specifically fetches data from the database.
    data = # code to fetch data
    return data

def sanitize_data(data):
    # This function specifically sanitizes the data.
    sanitized_data = # code to sanitize data
    return sanitized_data

def compute_result(data):
    # This function specifically computes a result from the data.
    result = # code to compute result
    return result
```
Not only this, but with a single responsibility, classes become far more testable! Writing unit tests for each responsibility, independently, ensures each part of the code works as expected.

## The DRY Principle

DRY, or "Don't Repeat Yourself" is another cornerstone of maintaining clean code. Repeated code not only introduces redundancies, but also creates nightmares when it comes to maintenance. By encapsulating common functionality into reusable functions, classes or modules, you adhere to the DRY principle and reduce risk of errors and inconsistencies.

Suppose you have a Python program in which you want to calculate the sum of elements in a list, and you need to do it in multiple places. Instead of repeating the code, a function can do this for you:

```
# Ignoring the DRY principle
numbers = [1, 2, 3, 4, 5]
sum1 = 0
for num in numbers:
    sum1 += num

numbers = [10, 20, 30, 40, 50]
sum2 = 0
for num in numbers:
    sum2 += num

# Keeping the DRY principle in mind
def calculate_sum(number_list):
    total = 0
    for num in number_list:
        total += num

numbers1 = [1, 2, 3, 4, 5]
sum1 = calculate_sum(numbers1)

numbers2 = [10, 20, 30, 40, 50]
sum2 = calculate_sum(numbers2)
```
By encapsulating repetitive tasks in functions, you're following the DRY principle! Making code more concise, easier to maintain, and less prone to errors.

## Code Comments Should Be a Last Resort

In the tech world, comments are often seen (and used!) as a necessary means to explain complex logic, document code, or provide context for future reads. While comments are valuable, Uncle Bob argues they should be used judiciously and sparingly. Here's why!

Clean code should be self-explanatory. This means the structure and naming within the code should convey clear intent and functionality without requiring additional comments. Code that follows naming conventions and is clear becomes almost a form of documentation itself.

Ironically, as Uncle Bob sardonically points out, comments can sometimes also mislead developers if they are not kept in sync with the code they describe. When code is modified, developers might forget to update accompanying comments, leaving a disparity between what the code does, and what the comments claim it does. This is the precursor to entering into needless bugs and misunderstandings.

## Conclusion

"Clean Code: A Handbook of Agile Software Craftsmanship” is a timeless resource for software developers, beginner and experienced alike, who aspire to be true craftsmen. By following these principles and adopting the mindsets presented in the book, devs can create software that isn't only functional, but also maintainable and adaptable to changing environments.