2

For example, does it make sense to refactor the following code:

a = a * 2;

as:

const int INT_TWO = 2;

// ...

a = a * INT_TWO;

My question hinges on the fact that the new constant conveys no extra meaning (as opposed to calling it, say, FOOBAR_FACTOR).

Fa773N M0nK
  • 151
  • 7

2 Answers2

19

No this is utterly pointless. Don't just extract literals to named constants without good reasons.

But do consider ways to explain why the a value has to be doubled in that context. That could involve:

  • a function name that explains the purpose of doubling, using terms from the problem domain. For example:

    function exponential_backoff(task, delay):
      while task() is not success:
        sleep(delay)
        delay = delay * 2
    
  • a comment explaining the reason for doubling

    // The backoff factor should increase the delay between retries.
    // A factor of at least two guarantees that the total load stays roughly constant
    // when the number of clients launching failing requests increases at a constant rate.
    delay = delay * 2
    
  • extracting the factor 2 to a constant or variable if it isn't obviously and necessarily always going to be 2.

    const BACKOFF_FACTOR = 2
    delay = delay * BACKOFF_FACTOR
    

The risk with naming variables or constants after themselves is that they might be changed in the future. For example:

const POINT_EIGHTEEN = 0.20  // actually a VAT rate but can't refactor
const TWO = 3

This is especially risky for constants that are extracted incidentally, and possibly have different meanings in different parts of the code. On the other hand, some constants are truly fixed and are not going to change, e.g. PI, KIBIBYTE = 1024, or SPACE = ' '. Apply your common sense to figure out what makes sense to name, and what doesn't.

amon
  • 135,795
9

Depends

If 2 has a meaning, like "number of pints on a quart", then yes. e g.

pints = quarts * PINTS_PER_QUART

So, the real question is, why are you multiplying a * 2? If giving 2 a meaningful name helps understand the code, you should do so.

user949300
  • 9,009