Using Constants in Code
Using constants in code is good, isn’t it?
I think this is one of the first things we’re being taught: use constants,
instead of literals. They increase the flexibility of the program (you
change the constant in one place, and then its value is updated everywhere),
and at the same time you make the code more explicit.
According to Code Complete[1], they have been shown to greatly aid program
maintenance.
And yet, more and more I find myself preferring literals to constants.
Yes, constants do improve code readability because they give a name to what
otherwise would be just a piece of data.
And yes, they have the advantage of centralizing the place for changes,
thus reducing the maintenance cost.
However, software design is always about tradeoffs, and constants are no
exceptions.
Using constants have a cost, because it increases the abstraction. In
particular, when reading the code, you need to go to the constant
declaration in order to know what’s there. Even with a good IDE, where you
can just jump to the declaration and then go back, it means losing the focus
and slowing down the understanding process.
For instance, a string constant like the name of a route: this is never repeated, and there is no advantage in centralization. Having it hidden in a constant name, makes it slightly more obscure.
Even more, the problem is in tests: test code should be extremely declarative.
Sometimes, constants can help in making it a bit shorter (e.g. very long
literals, or some large piece of data repeated multiple times), but more
often, you want to have an immediate idea of what’s being tested and the
actual test case – for instance, to compare against boundary values.
Which is much harder to know when using constants.
Overall, constants are an impressive and useful tool, and they should be used widely. And I agree that they help a lot in improving readability and maintainability. Yet, there are no silver bullets, and even usage of constant should be questioned while writing code.
[1] Steve McConnell, Code Complete 2nd Edition, Microsoft Press, page 308