by bryanlarsen · 11y ago · 0 comments
"By hard coding, I don’t mean you should spread magic numbers and strings across your project’s source code."
The first time you use a magic number or string, put it in directly. It's much easier to find and change in its home environment, and it keeps your code simpler and easier to understand.
Of course, once you use that magic number somewhere else, then you should introduce a constant -- you don't want to get in a situation where somebody changes it in one place but not the other. But until then, don't complicate things.
If you feel that I'm a heretic, then please define the constant where you use it (when it's only used in one place), rather than putting it in a header.
5
embedded in the code, and const int maxRetries = 5;
at the top of a file. Both are still hardcoded, but there's at least context for the number.If the name is required to understand the code, then putting your "const int maxRetries = 5;" in the code is better than a comment that says the same thing. Just don't put it at the top of the file. Put it on the line before you use it.
With numRetries=5, you can see he program makes retries. Withjust 5, that fact is hidden away in a method parameter somewhere.
And unless your IDE is ed+cat, there is no hunting needed to jump to a definition of a method. Having layers of generality makes code easier to read.
I completely disagree; adding extra indirection/generality always makes your code harder to understand. Adding meaningful/intuitive abstractions makes it significantly easier though.
My pet peeve is Java interfaces that only exist because you need to be able to mock the object in testing, but otherwise only have one real implementation. Especially when the name gives no indication that it's an interface, so you only find out after you pressed F3.
I'm guessing there are different tradeoffs in dynamically typed languages since the hardcoded number will also identify the type.
If it needs a name, name it where it's used!
I think of the "no magic constants" as a primitive precursor to the DRY principle. It was a good approximation for its time, but now we know better.
If someone were working on a different section of code and came upon a place where they needed maxRetries, but there was only a 5 defined somewhere, how would they know that it was already used once? Defining constants for anything that may be used multiple times saves the time of knowing/combing through every other section of code that could have already defined it.
It also encourages you (for better or worse) to use `maxRetries` in multiple places.
The value of 5 is, in the long run, meaningless. It could have easily been 3 or 10.