C Cima Mateo

Refactoring for Readability: A Developer's Journey in Estanciero

Working on the Estanciero project, a project of unknown description, often involves making code more understandable and maintainable. This post explores a recent effort to improve code clarity within the Estanciero project.

The Situation

Imagine a complex set of business rules represented by nested if-else statements. While functional, it can be difficult for developers to quickly grasp the logic and make changes without introducing bugs. This was the scenario in a particular module of Estanciero.

The Approach

Instead of directly modifying the existing code, the decision was made to refactor it using a combination of techniques aimed at enhancing readability and reducing complexity.

  1. Extracting Methods: Long blocks of code within the if-else statements were extracted into separate, well-named methods. Each method now represents a distinct step in the overall process. This modularization makes the code easier to follow and test.

  2. Replacing Conditionals with Polymorphism: In certain cases, the if-else logic was driven by object type. Polymorphism was introduced by creating a base class and specialized subclasses, each handling a specific condition. This eliminates the need for explicit type checking within the main logic.

  3. Introducing Helper Functions: Some repeated calculations or data transformations were encapsulated into dedicated helper functions. These functions provide a clear abstraction and prevent code duplication.

The Result

The refactored code is now significantly easier to read and understand. Each part of the process is clearly defined, and the logic is more self-documenting. The use of polymorphism reduced the complexity of the conditional statements. Here's a simplified example:

interface RuleInterface {
    public function apply(array $data): bool;
}

class RuleA implements RuleInterface {
    public function apply(array $data): bool {
        // logic for Rule A
        return true;
    }
}

class RuleB implements RuleInterface {
    public function apply(array $data): bool {
        // logic for Rule B
        return false;
    }
}

function processData(array $data, RuleInterface $rule): void {
    if ($rule->apply($data)) {
        // do something
    }
}

This illustrates how polymorphism allows different rule implementations to be applied without complex conditional branching.

The Takeaway

Prioritizing code readability can save time and reduce errors in the long run. Techniques like extracting methods, using polymorphism, and creating helper functions can significantly improve the clarity of complex code. Remember, code is read more often than it is written, so invest in making it understandable.


Generated with Gitvlg.com

Refactoring for Readability: A Developer's Journey in Estanciero
MATEO CIMA CRUCET

MATEO CIMA CRUCET

Author

Share: