Static Property Bug Caused by a Code Tool

With the following private properties at the top of a class.

private static readonly string taskTimeStampToken = string.Format("{0}Timestamp: ", taskToken);
private static readonly string taskToken = "[echo] @@";

What will this method in the same class print to the console when called.

public void Print()
{
 Console.Print(taskTimeStampToken);
}

For all you code geniuses that got this right away, I say shut up with your smug look and condescending tone as you say of course it prints

Timestamp:

So, why doesn’t it print

[echo] @@Timestamp:

Because taskToken hasn’t been initialized yet, of course. The order of static properties matter in your code. Don’t forget it, especially if you use a tool that reorganizes your code.

I really did know this ;), but this fact caused me about an hour of pain. I use a wonderful little tool called Codemaid and I use it to help keep my code standardized. One of its functions is to reorganize my code in a consistent format (e.g. private members above public, constructor before everything…).

I obviously never ran Codemaid on this particular file with code similar to above because unit tests have always passed. Well I had a code change in said file, Codemaid did its thing, it caused the order of the properties to flip like they are above, and unit tests started failing. It took me at least an hour before I took a deep breath and noticed that the properties flipped.

Lesson Learned

  • If you do any type of refactoring, even with a tool, make sure you have unit tests covering the file you refactor.
  • Use a diff tool to investigate mysteriously failing tests. It will give better visual clues on changes to investigate instead of relying on tired eyes.
  • Configure your code formatting tool to not reorganize your static properties, or request the feature to configure it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s