Curly’s Law

Ben Pereira - Aug 19 '23 - - Dev Community

You should answer to one thing, or do one thing only.

Curly’s law is a good concept to be used on software architecture because it reminds you that is always interesting to have your code loosely coupled and as simple as possible so you can reuse as much as you can.

You shouldn’t mix different levels of code (e.g. business rules with database access).

One simple example would be:

public class ImcCalculator {

    public static void main(String args[]) {
      double weightInPounds = 200;
      double heightMeters = 1.70;

      double weightInKg =  weightInPounds / 2.205;
      double imc = weightInKg / (heightMeters * heightMeters);

      System.out.println("Your IMC is " + imc);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here you can see that there is transformation from pounds to kg and also IMC calculation, so applying the concept of Curly’s Law the result is:

public class ImcCalculator {

    public static void main(String args[]) {
      double weightInPounds = 200;
      double heightInMeters = 1.70;

      final double imc = calculateImc(poundsToKg(weightInPounds), heightInMeters);

      System.out.println("Your IMC is " + imc);
    }

    public static double poundsToKg(final double weightInPounds) {
        return weightInPounds / 2.205;
    }

    public static double calculateImc(final double weightInKg, final double heightInMeters) {
        return weightInKg / (heightInMeters * heightInMeters);
    }
}
Enter fullscreen mode Exit fullscreen mode

You could even go further and create two different classes, one as converter of weights and the second as calculator.

In conclusion, having it separated will help you reuse on different places, make it easier to test it and understand it all in general.


If there is anything else that you would like to discuss leave a comment down bellow, see ya.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .