Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Less Magical Numbers

Less Magical Numbers

A quick look at how we can better comment "magical numbers" and constants in code

Lloyd Moore

January 19, 2024
Tweet

More Decks by Lloyd Moore

Other Decks in Programming

Transcript

  1. In the “dark times” we represented constants like this: double

    x = 2.718; We eventually started calling this a “magic number”, as it is just a number that has to be correct for the program to work.
  2. In time it was determined this was bad and we

    added more information: // The natural log of 1, e1 const double e = 2.718281; This is better, but for many applications it still isn’t good enough. Information is still missing:  Where did this number come from?  Why this particular precision?  Is there a traceability requirement to the specifications?
  3. Even when not formally required, having more information makes the

    number less magical: // The natural log of 1, e1 // Source: https://en.wikipedia.org/wiki/Natural_logarithm // 12 decimal places required for algorithm foo() // per requirement ABC-33920. const double e = 2.718281828459;
  4. But what if it is just a number that someone

    made up?: // Developer discretion const double x = 2.718; Then say so with some type of flag. This will let the reader know the number doesn’t have any particular significance!
  5. Real World Implications: This presentation is a result of a

    real world issue from an aerospace project. A constant had two different levels of precision between the flight software and the IV&V software, resulting in a failed verification. It took minutes to find the difference and a month to sort out value which was needed!