Single statement conditionals - why is the pattern not used for other code blocks?
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
//si开发者_StackOverflow中文版ngle statement
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
case
andbreak
statements 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.
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.
精彩评论