How dangerous can be “public const” while upgrading or fixing a component.

During my investigation I have noticed a source of potential problem for product upgrade where dev team should fix a bug or upgrade a component and distribute it.
So what will happen when during fix/upgrade process (I will call it upgrade) a value which was declared as public const was changed. For clear understanding we should see how build process is done. Actually during build process all variables which consume const will be hardcoded. It is not a problem when it is references from the same project, component will be rebuilt anyway. But what if it is referenced from another dll? The value will remain hardcoded and will contain old value.
Tools.dll MyConstants.cs
public const int DEFAULT_PORT = 80;
Service.dll Host.cs
So after upgrade of Tools.dll and change of the DEFAULT_PORT to 8080, Service.dll still will try to start service on 80 port! That is easy to test, just build a solution, copy components to another folder, change const value, rebuild and copy only updated DLL, run an application. You will see that application will show the old value.

To avoid troubles with component upgrade and constants it is strongly recommended to mark all constants as internal, or use them inside private or internal classes, classes which are not visible from the outside.
Another solution if you still want to use the same style of constant definition const should be changed to static readonly, which will create reference and value will not be hardcoded.
public static readonly int DEFAULT_PORT = 80;
Which will work correctly after component upgrade.
Happy coding.


Popular posts from this blog

Testing Azure Functions locally with automated integration test

Running Stockfish hosted in Azure function

Consuming Web API using JavaScript and XMLHttpRequest method