Last active
August 29, 2015 14:15
-
-
Save paulghaddad/c28e4d00e9a85e46d148 to your computer and use it in GitHub Desktop.
Level Up 7: Doesn't use magic numbers or constants, knows why
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Explain the problem with the use of magic numbers and constants. | |
The primary problem with magic numbers and constants is that we don't know their context. We don't know where they come from and their purpose. Furthermore, while the original developer may understand what they mean, in the future, he or other developers will be confused by their meaning. A secondary problem is that magic numbers and constants lead to code duplication. It is easy to continue reusing the same value throughout the code base without ensuring it is DRY. | |
2. Give an example of the use of 'magic numbers', and suggest a possible refactor. | |
Original: | |
class Circle | |
.... | |
def circumference(radius) | |
radius * 3.1415 | |
end | |
def area(radius) | |
3.14 * radius ** 2 | |
end | |
.... | |
end | |
Refactored: | |
class Circle | |
PI = 3.1415 | |
.... | |
def circumference(radius) | |
radius * PI | |
end | |
def area(radius) | |
PI * radius ** 2 | |
end | |
.... | |
end | |
Another example is the use of 12 for the number of months in a year. | |
3. Personally, I see people get too focused on this one sometimes. Can you name an example where moving away from 'magic' values isn't actually helpful? | |
There can be times when the context of a magic number is super obvious and will only be used once. A good example is the robot name exercise. It contains two methods, one that generates a random number, and a second that generates a random character. The methods contain a range for possible numbers (1..10) and letters ('a'..'z'). We could move these magical ranges into constants and name them: "DIGITS" and "LETTER". But this would probably be overkill. These ranges are only used once in the entire program, and their purpose can be inferred by the methods they are located in: "generate_number" and "generate_character". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment