Why Go Go War On Magic Numbers?

Magic numbers and, more generally, magic literals have been verboten in software development for decades. Just ran across a few more reasons why this advice is still sound.

By changing from “ThisMagicLiteral” to SomeClass.ThisMagicLiteral you not only get all the benefits of compile time checking you also make it easier to remove code that depends on the magic literal.

This might not seem like much of a benefit – especially since it can often take more time to type SomeClass.ThisMagicLiteral than “ThisMagicLiteral”. But given that the original authors may well be long gone by the time a given piece of functionality needs to be removed anything that makes removal less brittle is a big plus.

I’m also finding that the process of naming the literal itself aids in discoverability. Maybe it shouldn’t be SomeClass.ThisMagicLiteral. Maybe it should be SomeClass.TheFileThatThisMagicLiteralPointsTo. Or SomeClass.TheRegistryKeyThatThisMagicLiteralPointsTo. That extra bit of context might be enough to trigger an association in the mind of the developer maintaining the code (without access to the original developers).

It’s a big deal but is an often forgotten part of the software development lifecycle – disposal/decommissioning. Decommissioning is a lot easier if magic literals are replaced with constants. Lots of dependencies may have crept into the source. Often these dependencies aren’t even known to whoever happens to be maintaining the main block of code.

No comments:

Post a Comment