为什么每个人都告诉我编写这样的代码是一种不好的做法?
if (foo)
Bar();
//or
for(int i = 0 i < count; i++)
Bar(i);
Run Code Online (Sandbox Code Playgroud)
省略花括号的最大理由是它有时可以是它们的两倍.例如,下面是一些为C#中的标签绘制发光效果的代码.
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
for (int x = 0; x <= GlowAmount; x++)
{
for (int y = 0; y <= GlowAmount; y++)
{
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
}
}
}
//versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
for (int x = 0; x <= GlowAmount; x++)
for (int y = 0; y <= GlowAmount; y++) …Run Code Online (Sandbox Code Playgroud) 对于支持单一决策和没有括号的操作的语言,例如以下示例:
if (var == true)
doSomething();
Run Code Online (Sandbox Code Playgroud)
写这个的首选方式是什么?是否应始终使用括号,还是应将其使用留作个别开发人员的偏好?此外,这种做法是否取决于代码块的大小,例如在以下示例中:
if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
Run Code Online (Sandbox Code Playgroud) 在下面的例子中使用一个if与一个直接相结合的return可接受的做法,而不是在if里面有一块代码{}?这些在实践中是等同的还是其中一种方法的缺点?
Java中的一个例子:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
// Throw exception for fatal error (Servlet not defined in web.xml ?)
if( sc == null )
return; // old-style programming
// Careful with silent bugs ! Correct way of handling this is:
// throw new RuntimeException( "BookDetail: ServletContext is null" );
BookList bookList = WebUtil.getBookList( sc );
Run Code Online (Sandbox Code Playgroud)