A magic number overkill

Asked by At

I have a piece of code in which I call a function with argument of a string value. The string value is taken from a string array using the index.

if (validateRejectionCategory(rejectionData[0])) {
    ......
}

In this case is 0 still considered a magic number? Should I abstract 0 to a variable like REJECTION_CATEOGRY_POSITION? Does the function name not make it clear enough that the value would be a rejectionCategory?

Let me know your thoughts please.

1 Answers

1
Alistra On

In general extracting every numerical value to a constant is a bad habit. You have to maintain balance as with all things in life. Here it's clear that you want to validate the first element of rejectionData. Most uses of 0, 1, 2 are not magic, but are used in an algorithm.

You usually want to extract numeric values that aren't easily explainable in the context of code.

E.g. if your code looks like this in some main-like file:

app.modalTimeooutSeconds = 3.0

it's not really more readable to rewrite it as

let timeoutSeconds = 3.0
app.modalTimeoutSeconds = timeoutSeconds

unless you want to have a config file that are constants are stored, but you may not have enough constants to support having such a file.

Everything is context dependent and there are no good answers.