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 is supposed to mean. The first one’s the identity conversion, and the other two convert from centimeters to inches and the other way around.

Without the comments, the numbers would be magic numbers, which you’ve seen in Replace Magic Numbers with Constants. Here, the comments take out the “magic” and give a meaning to the numbers.

That’s a good start. After all, it’s clearly beneficial that the comments are there. But there’s a way we can make the code more meaningful on its own.

Consider the solution here:

 enum​ SmallDistanceUnit {
 
  CENTIMETER,
  INCH;
 
»static​ ​final​ ​double​ INCH_IN_CENTIMETERS = 2.54;
»static​ ​final​ ​double​ CENTIMETER_IN_INCHES = 1 / INCH_IN_CENTIMETERS;
»static​ ​final​ ​int​ IDENTITY = 1;
 
 
 double​ getConversionRate(SmallDistanceUnit unit) {
 if​ (​this​ == unit) {
 return​ IDENTITY;
  }
 
 if​ (​this​ == CENTIMETER && unit == INCH) {
 return​ CENTIMETER_IN_INCHES;
  } ​else​ {
 return​ INCH_IN_CENTIMETERS;
  }
  }
 }

We’ve basically applied Replace Magic Numbers with Constants here. While we did so, we removed the comments and merged them into the names of the constants. So in a way, we’ve “embedded” the comments into the code.

The code is much more self-explanatory. There’s more of it now since we’ve added several constants. The benefit of these constants is that they explain their meaning in their names. That’s why there’s no longer any need for additional explanation with comments: the comments have turned into actual code.

Comments always have a risk of becoming stale. Programmers rarely apply the same rigor to comments as they do to code. Someone might change the code but ignore the comment, or they might add a new conversion rate without documenting it.

If you capture the explanation of the code in things like naming, then it’s less likely that people will ignore it when they change code. As a rule of thumb, whenever you can merge a comment into the name of a constant, variable, field, or method, go for it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.26.108