Refactoring: The Art of Sweeping the Floor as You Walk

Refactoring: A Arte de Limpar o Chão Enquanto se Caminha

Introduction: Code That "Expired"

Have you ever opened a code file and immediately wanted to close it? That 300-line function full of nested if/else statements and variable names like data1 and temp. We have all been there.

Many developers believe that if code is working, we should not touch it. But in the real world of software development, code that does not evolve, rots. That is where Refactoring comes in.

What Is Refactoring, After All?

Refactoring is not "rewriting the system." According to Martin Fowler, one of the leading authorities on the subject, refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.

Let us look at a practical example. 

Replacing Magic Numbers with Constants

To illustrate how refactoring can be simple and powerful at the same time, let us look at the classic problem of 'magic numbers'. In the example below, see how simply swapping a stray number for a well-named constant eliminates the need for comments and makes the business rule obvious to anyone reading the code for the first time.

Before

if ($user->role === 1) {
    $bonus = $salario * 1.15;
}

After

const ROLE_MANAGER = 1;
const BONUS_PERCENTAGE = 1.15;

if ($user->role === ROLE_MANAGER) {
    $bonus = $salario * BONUS_PERCENTAGE;
}

The golden rule: If you changed what the code does (fixed a bug or added a feature), you were not refactoring. Refactoring is purely about design and readability.

Why Should You Care? (Especially If You Are Junior/Mid-Level)

  1. Reduced Cognitive Load: Well-refactored code lets you understand the logic in 5 seconds instead of 5 minutes.

  2. Time Savings (Technical Debt): What you do not clean up today becomes an obstacle tomorrow. Refactoring keeps delivery velocity steady over the long run.

  3. Professionalism: Writing code that a computer understands is easy. Writing code that other humans understand is what sets a senior developer apart.

When to Refactor? (The Rule of Three)

You do not refactor "for sport." There is a right time:

  • When adding a feature: If the current code makes the new implementation hard, refactor first to clear the path.

  • When fixing a bug: If the bug was hidden, the structure is probably confusing.

  • Code Review: It is the ideal moment to suggest clarity improvements.

3 Practical Techniques to Start Today

1. Extract Method

Have you ever felt that a function is trying to do too many things at the same time? When that happens, business logic gets buried in implementation details. Extract Method serves to name things explicitly: we turn logical blocks into small helper functions. Notice how, in the 'After' version, the main function tells a clear story of what is happening.

Before

// Process the list of users
function notifyUsers(users) {
    users.forEach(user => {
        // Check if the user can receive email
        if (user.active && user.emailVerified && !user.unsubscribed) {
            sendEmail(user);
        }
    });
}

After

function notifyUsers(users) {
    users.filter(canReceiveEmail).forEach(sendEmail);
}

function canReceiveEmail(user) {
    return user.active && user.emailVerified && !user.unsubscribed;
}

2. Replace Conditionals with Guard Clauses

One of the biggest enemies of readability is what we call the 'Pyramid Effect' — that endless succession of nested if statements that pushes code to the right. The Guard Clauses technique proposes inverting that logic: we validate the error and exit the function as early as possible. Compare how the reading flow stops being a maze and becomes a straight line.

Before

public function processarPagamento($pedido) {
    if ($pedido->status !== 'pendente') {
        if ($pedido->valor > 0) {
            if ($pedido->cliente->temCartaoSalvo()) {
                // Main payment logic here...
                return "Success";
            } else {
                return "Error: No card";
            }
        } else {
            return "Error: Invalid amount";
        }
    } else {
        return "Error: Order already processed";
    }
}

After

public function processarPagamento($pedido) {
    if ($pedido->status === 'processado') return "Error: Already processed";
    if ($pedido->valor <= 0)            return "Error: Invalid amount";
    if (!$pedido->cliente->cartao)      return "Error: No card";

    // Main payment logic here...
    return "Success";
}

Notice how linear the code became? Now you can read the business rule without getting lost in curly braces.

3. Names That Tell the Truth

If a variable is named list, it tells you nothing. If it is named expiredSubscriptions, it tells a story.

The Non-Negotiable Requirement: Tests

You never refactor without a safety net. Before changing a single line, make sure unit tests cover that functionality. If you change the code and the test fails, you broke external behavior. Without tests, you are not refactoring — you are just "tinkering and hoping."

Conclusion

Refactoring is not a one-off event that happens once a year. It is a daily habit. It is leaving the code a little cleaner than you found it. Not only does this help the project, it also shapes your mind to think more architecturally.

What about you? What was the most satisfying (or traumatic) refactoring you have ever done? Leave it in the comments!

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Engineering notes by email