
How can you prevent bit rot? Often in complex projects you will end up with some code that is just not doing anything. It may be part of another method. Instead of commenting it out or using an #if, you can use an if(false) and a pragma directive, as we show here.
This page describes ways you can reduce bit rot in C# programs.
Let's look at the original program. It simply computes an integer and prints it to the Console. The program works correctly, but as the requirements change, you find you no longer need to compute the integer or print it.
Program [C#]
using System;
class Program
{
static void Main(string[] array)
{
int value = 1 + array.Length;
Console.WriteLine(value);
}
}
In the next version, I wrapped the unneeded code in an #if directive. It is no longer compiled and in Visual Studio it will show as gray text. After wrapping it in the #if directive, I refactored the program so that the string[] formal parameter has a different identifier. At this point, the old code has become a victim of bit rot. It you remove the #if, it won't compile.
Program with #if directive [C#]
using System;
class Program
{
static void Main(string[] arrayName)
{
#if NOPE
int value = 1 + array.Length;
Console.WriteLine(value);
#endif
}
}In this version, I wanted to keep the unneeded code compiling so I wrapped it in an if(false) block. It will never be executed. This caused the compiler to issue a warning, which can be eliminated with #pragma warning disable. Now, we have a program that is validated at compile-time. The chances it will bit rot are much less. The chances it will fail to compile are zero.
Program with if(false) [C#]
using System;
class Program
{
static void Main(string[] arrayName)
{
if (false)
{
#pragma warning disable
int value = 1 + arrayName.Length;
Console.WriteLine(value);
#pragma warning enable
}
}
}
Dealing with parts of your code base that are not being used is challenging. Sometimes, the best approach is to comment statements out or use an #if directive. However, in this example we presented an alternative approach that preserves compile-time integrity of the code. With this approach the code won't need to be fixed to compile if other parts of the program are refactored.
Directives