Scott Penrose

Curly Braces

Scott is an expert software developer with over 30 years experience, specialising in education, automation and remote data.

The issue with braces...

OK I have a simple rule. Can I comment out a block of code?

Rules?

These rules are good:

  • Any naming standard is better than no standard.
  • There is no "one true" standard, we all have our preferences
  • If there is standard already in place, use it. Don't create another standard or muddy the existing standards.

Ext common style issue

ExtJS recommends this common form:

#!JavaScript
items: [{
    columnWidth: 0.13,
    layout: 'form',
    items: [{
        fieldLabel: 'Date',
        id: 'date'
    }]
},{ 
    columnWidth: 0.52,
    layout: 'form'
}]  
  • Can I comment out the first item in the list - NO.
  • Closing bracket is not the end of the block ! (line 9, just closes first object, not array). Blocks should always line up - e.g. if you open something (code like a while, if, sub, or here an array called items) then the closing bracket should line up with it, but not other brackets.
  • Cuddled "," - makes it hard to copy. It is still much easier to copy lines.
  • White space is free

My solution:

#!JavaScript
items: [
    {   
        columnWidth: 0.13,
        layout: 'form',
        items: [
            {
                fieldLabel: 'Date',
                id: 'date'
            }
        ]
    },  
    {
        columnWidth: 0.52,
        layout: 'form'
    }
]

Easier to read.

Perl... or most languages

Bad:

#!Perl
sub xyz
{
 ...
}

if (x < 3)
{
  one;
} else {
  two;
}

Good

Bad:

#!Perl
sub xyz {
 ...
}

if (x < 3) {
  one;
} 
else {
  two;
}

You can now comment out just the "else" block". In the first example you can't.

Parameters

I also do these with parameters to a function. When it comes down to it, what is the difference to that and a block. The common practice is to leave the first parameter inline, then spaces to line up the rest. Using spaces to line up these days is very 1980s... use Tabs.

#!Perl
myFuncCall(
  Param1,
  Param2,
  Param3
);
myComplexCall(
  q{
    SELECT
      *
    FROM
      a_table
    WHERE
      q = ?
  },
  undef,
  $q
);

Some rules

  • Don't cuddle "} else {"
  • Use tabs - don't waste time trying to line things up
  • Make sure that you can comment out a block
  • Keep syntax for blocks together
    • "if", "sub", "while" etc are part of the block, so put the open at the end of that line (unless split).

  • Coding