The concept of Magic numbers can be extended to more that numbers.Indeed, in your code, you may have some elements which can be like raw, hard coded without any variable to give it a meaning with a well chosen name. If(result = answer_to_the_ultimate_question_of_life_the_universe_and_everything) Moreover, the logic of your code will be much clearer, since you will be able to know the difference between to magic number when they don’t represent the same thing.Let’s modify the previous code example, and name the magic numbers:Ĭonst auto answer_to_the_ultimate_question_of_life_the_universe_and_everything = 42 When naming things, you will end up with one variable being used in several places, where you had the same number several time.After that, the refactor we mentioned will be super easy, as you will only have to modify the value of one variable. To do so, I encourage you to read this article about The Power Of Naming. The first thing to do, is to name everything.By that, I mean storing all your numbers into well-named variables. Those can be a few of the questions about the numbers that you can ask yourself when looking at such a code.The main problem of such number is that you have no idea of what they represent, which make the understanding of the code harder for new comers, or for people used to the code base too.Īnother problem with such number can be encountered when refactoring your code.Imagine that the 42 represent an error code, and it is now a valid result (since it’s the Answer to the Ultimate Question of Life, the Universe, and Everything □) and you have to modify it to 43.In all you code base, you have 42s and your task is to modify the right one into 43, but to let the 42s where they should not be change in 43.This example may sound a bit silly, but refactor of such nature does happen, and, if you aren’t prepare, it’s going to cost you a great amount of time, energy and money. What the numbers of this code mean ?Are the two ’42’ same information ?Is the parameter of otherfunction 3 because function also takes 3 as a parameter ?When returning -1, is it an error code, or something else ?
0 Comments
Leave a Reply. |