Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single statement conditionals - why is the pattern not used for other code blocks?

Tags:

c#

Just thought I'd see if somebody could explain why Anders decided that this is valid...

if(...)
   //single statement
else
   ///single statement

but this is not...

try
   //single statement
catch
   //single statement
like image 911
David Neale Avatar asked Feb 09 '11 10:02

David Neale


2 Answers

To quote from Framework Design Guidelines in the section about "General Style Conventions" this is said about braces:

AVOID omitting braces, even if the language allows it. Braces should not be considered optional. Even for single statement blocks, you should use braces. This increase code readability and maintainability.

There are very limited cases when omitting braces might be acceptable, such as when adding a new statement after an existing singöe-line statement is either impossible or extremely rare. For example, it is meaningless to add a statement after a throw statement:

if(someExpression) throw new ArgumentOutOfRangeExcetion(...);

Another exception to the rule is braces in case statements. These braces can be omitted as the caseand breakstatements indicate the begining and the start of the block.

What Anders thinks is subjective and argumentative, this is the recommendation.

You might also want to look at the section about bracing in the coding convention over at msdn.

like image 149
Filip Ekberg Avatar answered Nov 02 '22 19:11

Filip Ekberg


Probably because single statement conditionals are historically valid in curly brace languages, but the other patterns are not.

Since either example makes code less readable in general there is no good reason to introduce single statement support further than historically necessary.

If you image you extended single statement support to lots of code blocks you can quite easily see someone writing totally unreadable code. Personally I would avoid the first case too.

like image 28
James Gaunt Avatar answered Nov 02 '22 18:11

James Gaunt