Well formatted code is more readily debugged because SpacesAndBracketsAreYourFriends.  Use whitespace, brackets and curly braces to lay out code in a consistent format.  At first glance, well presented source code can be understood and fixed more quickly.  Elegant formatting also says much about a developer's attention to detail.  

If code is poorly formatted, the inbuilt features of the IDE can be used to beautify it.  It is generally expected that you will match the style of the existing codebase or match the project styles.

In the following code it is difficult to determine which artifacts relate to each other.

outFilename = fileName!=null?fileName+".pdf":type+"pdfFile.pdf";

A simple restructure and some well placed brackets makes the logic much clearer.

outFilename = fileName != null
              ? (fileName+".pdf") : (type+"pdfFile.pdf");

The same rule applies to curly braces.  Don't be afraid to add extra curly braces to replace the implied ones.

if (a == 1)
if (b == 2)
doSomething();
else
doAlternativeSomething();

The above code looks harmless enough but when indenting and braces are added it highlights one case where both doSomething() and doAlternativeSomething() are never called.  The code happens to need another function call to doSomethingElse() but this isn't obvious without braces and indentations.

if (a == 1)
{
    if (b == 2)
    {
        doSomething();
    }
    else
    {
        doSomethingElse();   // oops, the other case we missed
    }
}
else
{
    doAlternativeSomething();
}

It is a small thing.  You can be the world's worst programmer, but if you write beautiful code you will be respected for it.  Those who take pride in their work are more likely to become excellent programmers.

blog comments powered by Disqus