On self-documenting code

Take this piece of code:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);
    return text.Length;
}

What’s wrong with it?

It’s not very obvious what the magic number 5000 means? Does it mean 5000 years? 5000 minutes? 5000 the time it takes to run around Main Market Square in Kraków?

Sure, you can hover over the invocation (if you’re in Visual Studio) and see the tooltip

selfdocumentingcode

and see that the number denotes milliseconds, but then you (as well as the junior programmer who will maintain the codebase) have to remember what a millisecond is, and what it means to wait 5000 milliseconds.

The problem is, that millisecond is not the most natural unit of time for humans, so I can assure you that the first thing the aforementioned junior programmer will do when he inherits the code will be “refactoring” it, to this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);// waits 5 seconds
    return text.Length;
}

What this means, is not that junior developer is not very bright – no. Quite the contrary – he would be doing the right thing, only the wrong way. He would be increasing the readability of the code by documenting it. However, he would not have to do that, if the code was self documenting.

So how do we fix that? For example, like this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(TimeSpan.FromSeconds(5));
    return text.Length;
}