0

Is there a designated term for replacing hard constants (literals of any type) peppered throughout code with changeable constructs (can be a variable or #define or any similar mechanism)?

Basically, the overarching effect is integrating data into one place where one change is seen in multiple places.

For example:

int y = alpha(3);
.
.
.
if(beta(3)) x = a + b;
.
.
.
while(gamma(3)) {
    delta("hello");
}

becomes

int y = alpha(SCALE_FACTOR);
.
.
.
if(beta(SCALE_FACTOR)) x = a + b;
.
.
.
while(gamma(SCALE_FACTOR)) {
    delta(GREETING);
}
2
  • 1
    That is a form of abstraction.
    – Erik Eidt
    Jul 3, 2021 at 16:59
  • 1
    This is also know as the "introduce a constant" or "extract constant" refactoring (it's implied that it's a named constant). Jul 3, 2021 at 19:14

2 Answers 2

2

There’s no universally agreed single term for replacing a literal with a changeable symbol.

For numeric literals this kind of refactoring is commonly simply called:

since everybody knows that magic numbers are difficult to maintain and are replaced with less magic but more readable symbolic/named constants.

For nor non-numeric literals, the term “hard-coded” is generally preferred to “magic”.

Strings for example, unlike numbers, have the advantage to speak for themselves (at least sometimes) and be less repetitive and easier to find and replace. There is less incentive to replace them with symbols. Their replacement with constants is often done in the context of internationalization: the term used is “string extraction”, since all strings are then moved to a separate file and replaced with constants in the original source.

0

The practice of using named constants has no name more specific than the generally applicable "don't repeat yourself".

The opposite is called magic numbers, and it's a well-known antipattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.