Replace numbers with a constant that has a human-readable name explaining the meaning of the number.
This refactoring technique is used to replace hardcoded numeric or string values with named constants, in order to improve the readability and maintainability of the codebase. This can be useful when a codebase contains a lot of hardcoded values that make it difficult to understand or maintain.
For example, consider the following code, which uses hardcoded values to determine the tax rate for different types of products:
taxRate = 0.05;
}
taxRate = 0.1;
}
taxRate = 0.15;
}
}
To make the code more readable and maintainable, we can replace the hardcoded values with named constants:
taxRate =
}
taxRate =
}
taxRate =
}
}
In this example, we have replaced the hardcoded values with named constants. This improves the readability of the code by making it clear what the purpose of the values is and making it easy to change them in one place if necessary. Additionally, it's also easier to understand the meaning behind the number and it will be easier to trace if it is used in multiple places in the codebase.
Another benefit is that it allows for more flexibility in the codebase. For example, in the above example, if we need to change the tax rate for a certain product type, we can simply change the value of the corresponding constant without affecting other parts of the codebase. Additionally, by using symbolic constants, you can make your code more self-documented and easier to understand for other developers or for yourself in the future.
It's also worth noting that when implementing this technique, it's important to choose meaningful and descriptive names for the constants to improve the readability of the code. Also, it's a best practice to define the constants in a separate file or module and import them where they are needed, which makes it easier to manage and change them if necessary.