Replace Comments with Constants

 enum​ SmallDistanceUnit {
 
  CENTIMETER,
  INCH;
 
 double​ getConversionRate(SmallDistanceUnit unit) {
 if​ (​this​ == unit) {
»return​ 1; ​// identity conversion rate
  }
 
 if​ (​this​ == CENTIMETER && unit == INCH) {
»return​ 0.393701; ​// one centimeter in inch
  } ​else​ {
»return​ 2.54; ​// one inch in centimeters
  }
  }
 }

Comments are there to explain the code. But it’s even better if the code speaks for itself!

In this example, you see a unit conversion. It’s very similar to what you’ve seen in Group with New Lines, just for small instead of large distances. The method getConversionRate() returns a conversion rate number. For each number, there’s a comment that explains what the number ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.