57

A better way to handle magic values and constants?

 5 years ago
source link: https://www.tuicool.com/articles/hit/M3YzMfa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

It seems pretty well known that "magic values" in code are a bad idea and should be given descriptive names instead. Instead of this:

throw new Exception("invalid state: 0x02")

it's preferred to define "magic values" as constants:

Integer STATE_OK = 0x01;
Integer STATE_BAD = 0x02;
...
throw new Exception ("invalid state: {STATE_BAD}")

This works well thus far. However, what the user sees in either case is:

$ invalid state: 02

I am thinking of frameworks and tools designed for technical users here, not non-tech end users.

In my actual use case I was able to find the source code and search out the constant name of the value reported to discover the actual problem, but this is rather inconvenient and not always possible like when using closed source tools or the user isn't familiar with the given language.

As a developer I am interested in how this experience can be improved. On the surface it seems string values would be an improvement but that clearly doesn't scale well. Is this just a documentation failure and no better way to deal with it in the code? Ever see a drastically different approach?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK