2 Rookie Java Constants and Enums Pitfalls

In various code reviews I perform on Java and Groovy code I often see magic numbers and other random Strings littered all over the code base.

A magic number, for example, is the 4.2 in below (Groovy) code snippet:

if (swashbuckle >= 4.2) {
  ...
}

What does 4.2 mean?

My advise is to extract such a number to a constant and give it a meaningful intention-revealing name, so that we can all keep understanding our code.

every-time-platform-specific-constant

After refactoring into

if (swashbuckle >= MAX_ALLOWED_CAPACITY) {
  ...
}

even beginning developers understand the value of The Constant and start extracting values all over the place into constants. When I talk about enums it’s even more possible to write readable code, but quickly inexperienced developers quickly fall into the following traps. Continue reading “2 Rookie Java Constants and Enums Pitfalls”