Skip to content

On constants

Blokyk edited this page Jul 5, 2021 · 1 revision

Warning : This is mainly a downside of an imperfect versioning system

const fields should only be inlined for code in the same project (and so private const fields of a non-partial class are always affected), and should behave like static readonly otherwise. If this wasn't the case, this could happen :

  1. Barbra writes Physiconst, a library containing a bunch of physical constants. In version v3.6.2, one of the Planck's constants is declared as :

    public const double Planck = 6.62607004E-34;
  2. Alex writes a simple middle-ware that uses Barbra's library to calculate several properties of an object. Since Planck is a const, it gets inlined as 6.62607004E-34 into every expression that uses it.

  3. After a little while, Barbra founds out that the constant has been refined further, and thus changes its value in version v3.6.3, simply bumping the patch number because it's not that big of a deal, it just improves the precision :

    public const double Planck = 6.62607015E-34;
  4. Alex sees that there's a new version of the library and downloads it. He then runs his tests, expecting to get more precise result... but nothing changes. This is because the constant was inlined right into the assembly, thus it is still the same as the version it was compiled against, i.e. v3.6.2, and doesn't benefit from the increased precision. He would have to recompile his whole project to get the new precision.

Note : This is consequence of "patching" your libraries directly instead pf rebuilding your app. Should we really limit everyone just because of this ?