DEV Community

Jonatas de Moraes Junior
Jonatas de Moraes Junior

Posted on

DRY principle and the S of SOLID

Let's say an arbitrary and completely fictional javascript developer named Aristotle has to create a method that performs some area calculations based on a length. Let's watch him do it:

calculateArea(length) {
    return squareArea(length);
}
Enter fullscreen mode Exit fullscreen mode

Then Aristotle has been requested to do a very similar calculation, this time based on radius. So in order to respect the DRY (Don't Repeat Yourself) principle, he decides to rewrite the same method with new parameters:

calculateArea(param, type) {
    if (type == 'length') {
        return squareArea(param);
    } else {
        return circleArea(param);
    }
}
Enter fullscreen mode Exit fullscreen mode

This is okay, right? Because he is not creating two methods for calculating area, so Aristotle is not repeating himself. But then Aristotle realizes rectangles do exist, so he proceeds to do another small adjustment:

calculateArea(params[], type) {
    if (type == 'length') {
        if (params.length == 1) {
            return squareArea(params[0]);
        } else {
            return rectangleArea(params[0], params[1]);
        }
    } else {
        return circleArea(params[0]);
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope at this point you have realized what a mess this is becoming. Imagine having to deal with every shape in existence.

The problem here is with interpretation of the principle. Aristotle thinks that by having a single method for calculating areas, there will be no area calculations repeated and spread throughout his application. He is centralizing all area calculations in a single entry point. What Aristotle does not know though, is about the S of SOLID, or the Single Responsibility Principle.

If you think a bit deeper and couple these two principles together, you will realize that the calculateArea method didn't actually need to exist in the first place. This kind of method quickly grows in complexity thus also increasing cost of maintenance. The other methods for area calculation are self-suficient, isolated, and there is no repetition involved. Calculating the area of a square is a different responsibility than calculating the area of a circle.

Maybe this is a bit too exaggerated, but a similar pattern I often see is the boolean last parameter. When you have two very similar responsibilities, instead of creating two methods, you go and add a boolean parameter to the method signature, forking the flow with an if inside the method implementation. All is good, until you realize there is more than a single difference between them, so the boolean is not enough anymore, then you end up adding more than a boolean and more than a single if. And this goes on and on and on ...

When you see that pattern of nested ifs forming, take a step back and "check your principles". ;)

Latest comments (0)