Magic numbers and beyond

Are all magic numbers bad? To give the classic consultants answer - it depends. Take zero for example. If the zero is being used as an index into an array then the zero is a zero because all arrays start at zero. That's internal knowledge; knowledge that is part of the solution and a reflection of something from the problem. There is no way you can conceive of a change in the problem causing a change to that zero. So it's internal. So it's ok. But all things are relative. It might still be a good idea to refactor - to a higher level expression of the iteration perhaps. But most numbers are not internal, they come from the problem. If numbers such as this are not named then they are indeed magic numbers; they are numbers that reveal nothing of their origin.

Magic isn't limited to numbers though. Far from it. A magic number is a number and a number is an expression. So a magic number is also a magic expression. And of course, all expressions lie on the same magic-code continuum; some expressions are very intention-revealing, they're not very magic at all - while other expressions are very cryptic and thus qualify as magic expressions regardless of whether they contain numbers or not.

Beyond magic expressions we have magic statements, magic functions, magic classes, you name it, if its part of the code it can be magic. I think it's time we pushed the word magic into greater service. It's time we had a better vocabulary for hard to understand things. If you see a hard-to-understand X in code how about calling it a magic X.

4 comments:

  1. I really dislike the idea of extending the "magic" description upwards. I think it just adds credence to the notion of 'the ghost in the machine' - the idea that software of a certain size is inherently complex and buggy and that there isn't any other way. I used to work on a desktop app, and my boss just said that "software is just like that" - he didn't see the link between the smells in the low level code and the bugs in the overall software. But, then, they didn't even have any unit tests. Or tests.

    Personally, I'd much rather pull down the idea of "code smell" and call these "smelly numbers".

    ReplyDelete
  2. I think your idea of pulling smells down is a great one. Smelly numbers, smelly expressions, smelly statements. Like it. Thanks.

    ReplyDelete
  3. FWIW I think smelly numbers are an odour of magnitude better.

    ReplyDelete