单语句条件语句 - 为什么不用于其他代码块的格局? [英] Single statement conditionals - why is the pattern not used for other code blocks?

查看:118
本文介绍了单语句条件语句 - 为什么不用于其他代码块的格局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想过我会看到,如果有人可以解释为什么安德斯决定,这是有效的...

 如果(。 ..)
//单个语句
,否则
///单个语句

但这不是...

 
//单个语句
$抓b $ b //单个语句


解决方案

要从引用< A HREF =htt​​p://rads.stackoverflow.com/amzn/click/0321246756>框架设计指南中有关常规样式约定一节这是说,大约括号:




避免省略括号,即使语言允许它。括号不应
被认为是可选的。即使是
单语句块,你应该
使用大括号。这一增长代码
可读性和可维护性。



有非常有限的情况下,当
省略括号是可以接受的,
如添加时现有singöe线
语句之后一个新的语句
是不可能或
极为罕见。例如,它是
无意义的一个
语句添加语句:



如果(someExpression)抛出新的
ArgumentOutOfRangeExcetion(...);



另一个例外规则是在case语句
括号。这些
括号可以省略为情况
语句指示
开始时和块的开始。




安德斯认为什么是主观的,议论,这是他们的推荐。



您可能也想看看一节有关在的在MSDN编码约定过。


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

解决方案

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.

这篇关于单语句条件语句 - 为什么不用于其他代码块的格局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆