Magic Strings

August 2021

One piece of programming advice is that one shouldn't use numbers in code unless they're stored in a variable or constant. Using a number as a bare value – often called a "magic number" – gives no context as to why that number is being used.

totalWidth = getSize() + 272;

Why 272? Why not 113? Instead, one is encouraged to use constants.

final int WINDOW_PADDING = 272;
totalWidth = getSize() + WINDOW_PADDING;

This is better, because it prevents typos. But simply using a constant doesn't ensure readability. In string variables, there's an antipattern I'm calling magic strings.

final String USE_FOOBAR_SYSTEM = "use_foobar_system";

While the value is stored in a variable, the variable name merely repeats this value. The name doesn't help the reader understand what it's there for. These variables are no better than a numeric constant like:

final int THREE_HUNDRED_SEVENTY_TWO = 372;

The code does use a constant, but its name doesn't explain why the constant is there. Better to give it a name that explains what it's used for.

final String FOOBAR_SYSTEM_FEATURE_FLAG_NAME = "use_foobar_system";

This way, the name alone clearly indicates what it's used for. And clarity is a great goal to have in programming. As Harold Abelson and Gerald Jay Sussman have said,

…programs must be written for people to read, and only incidentally for machines to execute.

If you want to hear when I publish more, sign up for my mailing list!