DEV Community

Paulo Cesar
Paulo Cesar

Posted on

What I understand about Clean Code

When I started to study best practices for developing software, I imagined Clean Code was just a set of rules to keep code readable. In part, that's true. However, some of these rules don't apply to all types of code, and certainly, they aren't achieved just by reading a book.

Uncle Bob

Clean code

A few months ago, I re-read Robert C. Martin's classic, Clean Code, and had a completely different perspective than the first time I read it. When I was starting university, I couldn't fully understand most software problems, let alone how to solve them. And this is probably the greatest mistake of junior developers: Clean Code is not for beginners.

"What if you were a doctor and had a patient who demanded that you stop all the silly hand-washing in preparation for surgery because it was taking too much time? Clearly the patient is the boss; and yet the doctor should absolutely refuse to comply. [...] So too it is unprofessional for programmers to bend to the will of managers who don't understand the risks of making messes."

Considering this complexity for beginner developers, in this article I wanted to highlight the key points I found most relevant while reading the book, as well as share a few practical lessons from my own career.

Functions

A well-written function must have just one responsibility: it must do one thing, do it well, and do only that. When we try to bundle multiple responsibilities into a single function, the code becomes hard to read, test and maintain.

Consider the following example, where a function handles multiple tasks to save and notify users:

function saveAndNotifyUser(user) {
    // Validates user data
    if (!user.name || !user.email) {
        throw new Error('Incomplete user data.')
    }

    // Saves to the database
    database.save(user)

    // Sends a welcome email
    emailService.sendEmail(user.email, 'Welcome!', 'Thanks for signing up!')
}
Enter fullscreen mode Exit fullscreen mode

That function violates the Single Responsibility Principle because it combines validation logic, data persistence and email sending.

After refactoring, each responsibility is delegated to a specific function:

function validateUser(user) {
    if (!user.name || !user.email) {
        throw new Error('Incomplete user data.')
    }
}

function saveUser(user) {
    database.save(user)
}

function sendWelcomeEmail(user) {
    emailService.sendEmail(user.email, 'Welcome!', 'Thanks for signing up!')
}

function processUserRegistration(user) {
    validateUser(user)
    saveUser(user)
    sendWelcomeEmail(user)
}
Enter fullscreen mode Exit fullscreen mode

Now, each function has a single responsibility, making the code easier to read, modify and maintain in the future.

Comments

Although comments are useful in many cases, we should prioritize writing self-explanatory names to prevent unnecessary explanations. Comments should only clarify complex parts of the code. In excess, they clutter the codebase.

Look this example:

/** Day of the month **/
private number dayOfMonth;
Enter fullscreen mode Exit fullscreen mode

This comment is completely unnecessary, as the attribute name explains exactly what it represents. We can clean this up by eliminating the redundant comment:

private number dayOfMonth;
Enter fullscreen mode Exit fullscreen mode

Now, the attribute is clearly named, making comments completely unnecessary.

Consider a function where the comments are redundant because the code explains its own purpose:

// Calculates the average of a list of numbers
function calculate(numbers) {
    let totalSum = 0
    for (const number of numbers) {
        totalSum += number
    }
    return totalSum / numbers.length
}
Enter fullscreen mode Exit fullscreen mode

In this case, the original function name isn't descriptive enough, so a comment was added to explain what it does. We can refactor this by choosing a more appropriate name:

function calculateAverage(numbers) {
    let sum = 0
    for (const number of numbers) {
        sum += number
    }
    return sum / numbers.length
}
Enter fullscreen mode Exit fullscreen mode

Now, this function name conveys exactly what it does, making the comment completely unnecessary.

Objects and data structures

A good object-oriented programming design focuses on exposing the operations that can be executed and hiding implementation details. This promotes encapsulation and simplifies code maintenance.

Consider the following code:

class Circle implements Shape {
    private center: Point;
    private radius: number;
    private PI = 3.14159;

    public calculateArea(): number {
        return this.PI * this.radius * this.radius;
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice that we don't need to know what the PI value is, or even how the area is calculated. What matters is that the Circle class provides a public method, calculateArea(), that encapsulates the implementation details. Anyone using the class simply needs to call this method without worrying about internal details.

Avoid reusing variables in different scopes for different purposes, because this can cause confusion and make the code harder to read. Consider the following example that violates this practice:

let result = 0;

// Calculates the area
result = PI * radius * radius;

// Uses the same variable for the perimeter
result = 2 * PI * radius;
Enter fullscreen mode Exit fullscreen mode

In this case, using the same result variable to store different values (area and perimeter) can be confusing. A better approach would be to use separate variables:

const area = PI * radius * radius;
const perimeter = 2 * PI * radius;
Enter fullscreen mode Exit fullscreen mode

Now, the code is much clearer, self-explanatory and less prone to errors.

Error handling

In the past, the techniques to handle and report errors were very limited. The options generally involved creating an error flag or use error codes that needed to be constantly checked. This made the code more verbose and less readable.

Consider the following example that uses multiple checks to handle fundamental execution errors:

function shutdownDevice() {
    const handle = getHandle(DEV1);

    if (handle !== DeviceHandle.INVALID) {
        const record = retrieveDeviceRecord(handle);

        if (record.getStatus() !== DEVICE_SUSPENDED) {
            pauseDevice(handle);
            clearDeviceWorkQueue(handle);
            closeDevice(handle);
        } else {
            logger.log('Device suspended. Unable to shut down.');
        }
    } else {
        logger.log('Invalid handle for: ' + DEV1.toString());
    }
}
Enter fullscreen mode Exit fullscreen mode

Although functional, this code is verbose and repetitive. It mixes validation, execution and error-handling logic in a single place, making it harder to read and maintain.

Instead of manually checking multiple conditions, a clearer approach is to throw exceptions to catch errors. This allows you to centralize error handling and focus only on the main function flow. Take a look at the refactored code:

function shutdownDevice() {
    try {
        tryToShutdownDevice();
    } catch (error) {
        logger.log(error.message);
    }
}

function tryToShutdownDevice() {
    const handle = getHandle(DEV1);

    if (handle === DeviceHandle.INVALID) {
        throw new Error('Invalid handle for device: ' + DEV1.toString());
    }

    const record = retrieveDeviceRecord(handle);

    if (record.getStatus() === DEVICE_SUSPENDED) {
        throw new Error('Device suspended. Unable to shut down.');
    }

    pauseDevice(handle);
    clearDeviceWorkQueue(handle);
    closeDevice(handle);
}
Enter fullscreen mode Exit fullscreen mode

Now, the main code (shutdownDevice()) is more concise and focused on the main flow, while the validation details and error throwing were moved to tryToShutdownDevice()

Unit tests

Tests must be clear, simple and consistent. They need to communicate as much information with as few expressions as possible, making it clear what is tested and the expected result.

General test structure

  • Build: Configure the necessary data or environment for the test;
  • Operate: Run the operation or action to be tested;
  • Check: Verify that the result is as expected.

Consider the following example:

it('should return data in XML format', () => {
    const page = createPageWithContent('TestPage', 'test content'); // 1️⃣ Build

    page.sendRequest('TestPage', 'type:xml'); // 2️⃣ Operate

    expect(page.contains('test content')).toBe(true); // 3️⃣ Check
});
Enter fullscreen mode Exit fullscreen mode

When you are writing a test, remember: clarity and focus are more important than covering multiple cases in a single test. This keeps maintenance simple and efficient, helping pinpoint issues more precisely.

Classes

A class name should clearly reflect its responsibility. Classes need to be small, with a single purpose and an unambiguous name.

SRP - Single Responsibility Principle

Each class must have just one responsibility and one reason to change. This simplifies the maintenance and code reuse.

Simple example:

class Sql {
    Sql(table, columns)
    create()
    insert(fields)
    selectAll()
    findByKey(column, value)
    // ...
}
Enter fullscreen mode Exit fullscreen mode

When a class accumulates many responsibilities, it violates the SRP, as in the case of the Sql class that has multiple methods. Modifying any part can affect other functionalities, increasing the risk of failures.

SRP refactor

class Sql {
    constructor(table, columns) { }
    generate() { }
}

class CreateSql extends Sql {
    generate() { }
}

class SelectSql extends Sql {
    generate() { }
}

class InsertSql extends Sql {
    generate() { }
}
Enter fullscreen mode Exit fullscreen mode

Now, each class has a single, clear responsibility, following the Open-Closed Principle (OCP), which states that classes must be open for extension, but closed for modification.

What I understand about Clean Code

Clean code is not something you learn all at once or simply by reading a book. It's a continuous journey that requires practice, reflection, and evolution. Personally, I keep learning with each new project. What I have learned over time is that the true skill in writing clean code comes from experience and the ability to recognize what can be improved.

Furthermore, as Kent Beck stated, a "simple" software project must follow a few fundamental rules to maintain quality and keep code clear:

  1. Run all the tests;
  2. Eliminate duplication;
  3. Clearly express the programmer's intent;
  4. Minimize the number of classes and methods.

These rules are presented in order of importance and serve as a valuable guide for those looking to write better—and clear—code too. Apply these practices in your daily work and see how your code becomes clearer and stronger over time.

Top comments (0)