Coding Best Practices: Dealing with magic values.
Magic values or magic constants are literal values that are used in code without clear definition of their meaning or purpose (Hence the name magic constants). These literals are considered as code smell as they degrade the maintainability of a software by making business rules related to constant values unreadable. Consider the sample below:
FIGURE 1: The literals .30 and 125 are considered magic values.
In Figure 1, you would notice that the literal values .30 and 125 are used. These literal values are a good sample of magic numbers which are considered as code smell due to the fact that they prevent readers from interpreting their purpose.
Writing software in this approach makes life easy for the original authors since they understand the purpose of the values. In contrast, magic numbers are notorious for punishing developers that would maintain the code. Developers have to spend time figuring out the purpose and story behind the numbers. Magic values start to evolve to a very costly problem (Next to the null reference exception, I believe this code smell is another million dollar problem today) as time passes by because:
- Original authors may leave the company.
- Original authors may work on different projects and end up forgetting the purpose of the values.
- Source code might be maintained by other team members (Surprise for you Kiddos :D).
Solution: Busting the f*cking magic values.
FIGURE 2: The literals .30 and 125 are now placed on self documenting constant values.
In Figure 2, the magic values were extracted out of the original method and defined using self documenting constant variables. Following this approach helps in improving the maintainability of the code in the following ways:
- The purpose of the values are now identifiable.
- The values can now be re-used in future methods that would be written.
- Applying changes for magic values used in different sections is easier.
The existence of the magic values introduces maintainability problems and should therefore be avoided at all means through the use of self documenting variables.
Be kind to your future selves.