Articles

February 01, 2020

Code Smells: How to identify and prevent Code Bloaters

When building software, it is common to question the quality of the code we are writing. We try to apply a few basic rules to make our code more efficient and easier to maintain. However, we do not always follow those rules — especially when we are starting out or lack technical experience. Very often we only care about making the code work, without considering future maintenance or the burden we leave for other developers.

What are Code Smells?

Code Smells are common practices in software development that can lead to problems. They are parts of the code that make you think: "this is going to blow up someday". Some Code Smells are so obvious that they come with highlighted comments protecting the block: "Be careful when touching the code below!!!!!". When you "smell it", congratulations — you have found a Code Smell.

As Martin Fowler puts it: "The best smells are ones that are easy to spot and most of time lead to really interesting problems."

Code Bloaters

In this article we will focus on Code Bloaters, a specific category of Code Smell. Bloaters are the most common signs of rot in a codebase. They do not appear overnight — they grow as we keep feeding classes and methods without control until they become gigantic. In my opinion, these are the hardest cases to refactor.

To spot them, take a look at your code and check for long methods, huge classes (the ones with thousands of lines), chunks of code carrying the same set of variables over and over (known as Data Clumps), unnecessary comments or duplicated code.

Large classes or methods

A common bloater is a class or method that grows too big. This makes the code hard to understand and maintain. Large classes usually hold too many responsibilities and can be split into smaller, more specialized classes. Large methods can be broken down into smaller, more specific ones, improving readability and reuse.

class Order {
    // Class properties and methods

    public function calculateTotalAmount() {
        // Complex calculations to get the order total
        // ...
    }

    public function printOrderDetails() {
        // Printing the order details
        // ...
    }

    // More methods...
}

Methods with too many responsibilities

Another common bloater is a method that performs several different tasks. This violates the single responsibility principle, where each method should have one well-defined responsibility.

class ShoppingCart {
    // ...

    public function checkout() {
        // Cart validation
        // Total calculation
        // Order generation
        // Inventory update
        // Confirmation emails
        // ...
    }

    // ...
}

Here the checkout() method performs many steps, from validating the cart to sending confirmation emails. It would be better to split those responsibilities into separate methods such as validateCart(), calculateTotal(), generateOrder(), updateInventory() and sendConfirmationEmails().

Unnecessary comments

Excessive and unnecessary comments can also point to Code Bloaters. Clean, well-structured code should be self-explanatory most of the time. Comments should explain the intent behind the code, not what the code is doing.

// Get the customer name
$name = $customer->getName();

In this case the comment is redundant, since the code already speaks for itself.

Duplicated code

Duplicated code, also known as "clone code", is another example of a Code Smell. Duplication makes maintenance harder, since any change has to be applied in several places.

class ProductService {
    // ...

    public function calculateDiscountedPrice($price, $discount) {
        $discountedPrice = $price - ($price * $discount / 100);
        return $discountedPrice;
    }

    public function calculateSpecialPrice($price, $specialDiscount) {
        $specialPrice = $price - ($price * $specialDiscount / 100);
        return $specialPrice;
    }

    // ...
}

This duplication can be avoided with a single generic method that calculates the discounted price, taking the discount as a parameter.

Data Clumps

Data Clumps are groups of identical or similar variables that keep showing up across different parts of the code. This repetition signals a missing abstraction.

class Customer {
    public $name;
    public $email;
    public $phone;
    public $address;
}

class Order {
    public $customerName;
    public $customerEmail;
    public $customerPhone;
    public $customerAddress;

    // ...
}

A better approach is to create a single Customer class and reference it from Order, avoiding duplication and improving how the data is organized.

Conclusion

Identifying and preventing Code Bloaters is essential to keep code clean, efficient and maintainable. By applying good programming practices and performing proper refactorings, we can avoid these Code Smells and improve the overall quality of our code.

Always remember Martin Fowler's words: "The best smells are ones that are easy to spot and most of time lead to really interesting problems."

References


Source: Originally published on Medium

Portrait photo of Dionatan Melo, senior software engineer

Written by

Dionatan Melo

Senior Software Engineer