DEV Community

Cover image for Curly’s Law
Ben Pereira
Ben Pereira

Posted on • Edited on

Curly’s Law

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.

Top comments (3)

Collapse
 
cicirello profile image
Vincent A. Cicirello

Hi. Nice post. This is more of a suggestion on post formatting than it is on your content. You can improve your code blocks with syntax highlighting by putting language name, in this case Java, immediately after the 3 backticks that start the code block.

Collapse
 
bendlmp profile image
Ben Pereira

nice! thanks the tip Vincent :)

Collapse
 
cicirello profile image
Vincent A. Cicirello

You're welcome