Constants [VD5]

Constants [VD5]

Tip VD5

Constants should be named based on the conceptual idea they’re represent, rather than their literal values, to communicate more information to readers.

“Constants” are variables that are essentially unchanged after receiving their values (typically initialized at compile-time when a code is being built or load-time when a program is being loaded into memory). The unchanging nature of this data during runtime is worth considering when naming constants.

Don’t name constants directly based on their literal values. Constants are often initialized with literal values, which can make this tempting. A name like TEN = 10 is typically bad as it communicates less when used elsewhere in code, and if the literal value needs to change, the name becomes outdated and would require effort to update code where it is used.

Do name constants after the conceptual value they’re intended to represent. Taking the 10 example above, if that number is intended to represent the number of employees, EMPLOYEE_COUNT is a better name. When that constant is used elsewhere, the meaning of the value in terms of the problem being solved is more evident. If the number of employees changes, you can change the value assigned to the EMPLOYEE_COUNT constant without updating other code.

The following shows several examples of poor constant names (that don’t communicate much more than the literal value) transformed into better constant names (communicating higher-level meaning):

Say goodbye to blindsided code updates ad.png
Reclaim your coding time reduce meetings ad.png