I’ve started using Checkstyle on my code base. One of the checks I’ve enabled is magicnumbers, which as its name implies, ensures your code isn’t using magic numbers.
As a result, I found some code that was doing the following:
final double minutes = timeInSeconds / 60;
How many times have you done that? Or wanted to convert milliseconds to minutes or various others? Created a constant with 60*60*24 for conversions? Doing a bit of Googling, I learned that in Java 6, as part of the Concurrency updates, the JDK now has a TimeUnit class. This then allows one to do the following instead:
final double minutes = TimeUnit.SECONDS.toMinutes(timeInSeconds);
That’s much cleaner, and less prone to both misunderstanding and errors.