DEV Community

Discussion on: Magic Numbers (in programming)

Collapse
 
scottshipp profile image
scottshipp • Edited

I also have found it helpful over the years to learn that many of the classic examples of "Magic Numbers" have their own domain-specific static values within utility classes in the standard library or a readily-available third-party library (like Apache Commons). A few examples:

Much of the time hard-coded math can be replaced with these utilities. For example, instead of calculating five minutes in milliseconds like:

long fiveMinutes = 300000;
Enter fullscreen mode Exit fullscreen mode

or (only slightly more comprehensible)

long fiveMinutes = 5 * 60 * 1000;
Enter fullscreen mode Exit fullscreen mode

Do it this way instead:

Duration.ofMinutes(5).toMillis()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anthonyjdella profile image
offline

@scottshipp Great points! Thanks for the examples!

Standard and third-party libraries might have common values (like the ones you mentioned). The cool thing with my example is that you can customize them yourself since a library won't know less common values (such as an address).