If you know the Betteridge’s law of headlines, you know that the answer is no. I discussed it many times with my colleagues and it’s time to define rules for what constitutes as “magic string/number”

Of course, that’s because again someone somewhere pointed out that value could be extracted to constant.

It’s the same story as always: when you start programming you don’t give a damn about some constants. I mean, you know your code, right? All values are clear in code and besides, why would I want to change them?

Then you learn that there are many reasons for extracting values to constants:

  • reusing values - so you are sure that all places have exactly the same value
  • maintainability - one point of truth where change of requirements implies change in only one place
  • readability - because name explain value
  • configuration - often you want to have all configuration in one place, so constant is a must

Quick example:

public String sendSomethingToServer(String data) {
        int returnValue = sendToServer(data);
        switch (returnValue) {
            case 1: return "That's cool";
            case 3: return "That's bad";
            default: return "I have no idea";
        }
}

That’s bad. At some point in the future someone will not know what 1 or 3 means. This is perfect place to introduce constants:

private static final int RESPONSE_OK = 1;
private static final int RESPONSE_BAD = 3;

public String sendSomethingToServer(String data) {
    int returnValue = sendToServer(data);
    switch (returnValue) {
        case RESPONSE_OK: return "That's cool";
        case RESPONSE_BAD: return "That's bad";
        default: return "I have no idea";
    }
}

More readable indeed.

And you do it all the time, because you are a good programmer, you follow best practices. That’s good.

But is it always a good idea to extract some value to constant? Definitely not. So… when you should not do it? When it gives you nothing.

Should this be extracted?

String returnValue = sendToServer(data);
switch (returnValue) {
    case "OK": return "That's cool";
    case "BAD" : return "That's bad";
    default: return "I have no idea";
}

You already know why magic value are bad, so if extracting magic value to constant is not beneficial in any way - why do it?

If you think about creating constant, first ask yourself these questions:

  • Can you reuse this constant?
  • Can you easily change a few values at once?
  • Does it improve readability?
  • Is it part of configuration?

Four times “No”, you’re out.

Seems legit

Of course by “you’re out” I mean you should not extract value to constant, because what’s the point? Blindly following best practices is a bad thing (but not worse than blindly following bad practices, so it’s something).

If you want more examples and more text, check this questions on Stackoverflow and StackExchange Software Engineering