Be a Developer, not a Blender

Small Classes and Methods

This is a good practice that is ignored by many developers. We gain a lot of advantages when having smaller classes/methods:

  • Easy to Maintain: we can edit the code without the need of reading a lot of lines
  • Easy to Test: makes tests easier; the components are isolated
  • Increase Cohesion: The class will have defined behavior
  • Readability: It is easier to read and understand the code

How that I can reduce the code when it’s huge and difficult to read? Eclipse, Intellij and Netbeans have tools that will extract the code into methods automatically. The shortcode to this feature will change between the IDEs, but you will get something like

public void paymentMethod1(final BigDecimal valueAsBigDecimal)
    final NumberFormat format = new DecimalFormat("#0.00");
    final String formatedValue = format.format(valueAsBigDecimal.doubleValue() * 100);
    final int myValueAsInt = Double(formatedValue).intValue();
 
    // do something
}
 
public void paymentMethod2(final BigDecimal valueAsBigDecimal)
    final NumberFormat format = new DecimalFormat("#0.00");
    final String formatedValue = format.format(valueAsBigDecimal.doubleValue() * 100);
    final int myValueAsInt = Double(formatedValue).intValue();
     
    // do something
}

We could extract the common code in the sample above. Take a look at how the code looks reduced:

public void paymentMethod1(final BigDecimal valueAsBigDecimal)
    final int myValueAsInt = MoneyHelper.convertToInt(valueAsBigDecimal);
    // do something
}
 
public void paymentMethod2(final BigDecimal valueAsBigDecimal)
    final int myValueAsInt = MoneyHelper.convertToInt(valueAsBigDecimal);
 
    // do something
}

With smaller code it is possible to find methods and attributes very quickly, without the needing to scroll through several lines. Remember that sometimes we will not open the code inside an IDE, but in desperate times we will open it in a browser or in a text editor.

Conclusion

Always reduce the length/width of your methods/classes.

2 thoughts on “Be a Developer, not a Blender

Leave a Reply to uaihebert Cancel reply