The Dangers of Magic Values

November 17, 2018
Blog

A regression recently appeared in a legacy codebase we’re maintaining: empty values were being saved to the database, which was causing downstream problems. There were in-code checks to prevent that from happening, but the checks weren’t being triggered – empty-value saves were erroneously being allowed to proceed.

After some investigation, we discovered that it was caused by a special magic value used to represent NULL, coupled with a recently-added rounding mechanism. Since 0 is a valid value for the quantity in question, the original developers of the code chose -9999.9999 to indicate a non-value. When the rounding mechanism was introduced, it failed to account for the precision of the magic value, so false negatives of the form “isNull = (-9999.99 != -9999.9999)” occurred.

This highlights the risk of overloading a scalar value to represent both value and state. Using a strongly-typed class object in place of the simple scalar would be a better approach. Better yet are .NET’s nullable types (e.g. “decimal? temperature”, “int? sensorId”). Nullable types have many added benefits, including built-in sematic clarity with APIs like “HasValue()” and support for NULL-comparisons.

Calgary

1700, 308 4th Avenue SW
Calgary, AB T2P 0H7
Canada
403.242.4361

info.calgary@arcurve.com

Houston

5090 Richmond Avenue
Houston TX, 77056
USA
713.422.2135

info.houston@arcurve.com

© 2022 Arcurve. All rights reserved.