Saturday, January 23, 2010

The whitespace and indentation debate

Nothing annoys me more than having to argue over whitespace and indentation. Where should we stick the braces? Spaces vs Tabs? Can't we find something more useful to argue over?

Long ago I read the only to end the pointless whitespace debate, is to have the compiler reject random whitespace. I thought that was a very good idea, and today I'll talk about it.

In the beginning whitespace didn't matter, it was there for the human, and the program ignored it.   But that caused an annoying problem - you ended up needing tokens like '{' ';' and '(' and then you needed to argue about how you arranged the code around those tokens.  For example:

ProcessIncomingDogs(List<Dog> dogs)
{
    ...
    if (dogs>1)
    {
        RunAway(smallDogs,speed.Fast);
        Log("SmallDogs Ran Away Fast");
    }
    Log("EveryOne Ran Away that needed to");
    ...
}

I'm happy to say we're making progress, python gets rid of the annoying braces and instead denotes blocks via whitespace instead.  As a result many python programmers feel that python looks like sudo code. For Example:

def ProcessIncomingDogs(dogs):
    ...
    if dogs>1:
        RunAway(smallDogs,speed.Fast)
        Log("SmallDogs Ran Away Fast")
    Log("EveryOne Ran Away that needed to");
    ...

This is good, but there is annoying problem with python. Which whitespace will you use? Spaces or Tabs? Since whitespace implies meaning, mixing spaces and tabs makes real python bugs.

I was very excited to discover that F#, which also relies heavily on whitespace, does not allow tabs for whitespace. I'm thrilled!  Finally the whitespace debate is over in F#. Hopefully more languages will follow F#'s lead. For example:

let ProcessIncomingDogs dogs =
    ...
    if dogs > 1 then
        RunAway smallDogs speed.Fast
        Log "SmallDogs Ran Away Fast"
    Log "EveryOne Ran Away that needed to"
    ...

By the way, if you are lucky enough to use C#, an excellent way to enforce consistent coding is StyleCop. It has a sane set of rules and decent tooling.  For example the StyleCop for Resharper plugin can perform as you type auto-correction to fit the StyleCop coding convention.

May you never have to waste your life arguing over whitespace and indentation again!

No comments: