这两个例子有什么区别:
if(firstchek)
{
if(second)
{
return here();
}
else
{
return here();
}
}还有这个:
if(firstcheck)
{
if(second)
{
return here();
}
return here();
// else code without else
}
// code without else
// else code is here
return here();发布于 2010-07-23 15:59:51
这段代码:
if (someCondition)
{
foo();
return;
}
bar();
return;与以下内容相同:
if (someCondition)
{
foo();
}
else
{
bar();
}
return;唯一的区别是可读性。有时一种方式更具可读性,有时另一种方式更易读。参见Refactoring: Replace Nested Conditional with Guard Clauses。
嵌套条件
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};保护条款
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
}; 发布于 2010-07-23 15:58:30
假设没有其他代码,则在代码路径和执行内容方面没有区别。
通常,主要区别在于,在指定else子句时,仅当if中的表达式计算为false时才会运行。如果不指定,代码将始终运行。
更新
这一点:
if(second)
{
return here();
}
else
{
return here();
}还有这个:
if(second)
{
return here();
}
return here();将与以下内容相同:
return here();为什么?因为无论second的计算结果是什么,您都在做同样的事情,所以检查是多余的。
发布于 2010-07-23 16:22:51
这两组代码在语义上是相似的。也就是说,它们将在运行时执行相同的操作。但是,您是否应该使用一种形式或另一种形式取决于情况。除了所需的语义之外,您的代码还应该表达您的意图。
如果代码的意图是做一个或另一个,那么保留其他的,这样你的意图是明确的。例如。
if (withdrawAmmount < accountBalance)
{
return Deduct();
}
else
{
return ArrangeCredit();
}但是,如果目的是在特殊情况下做第一件事,那么可以随意省略其他事情。例如。
if (parameter == null)
{
return NothingToDo();
}
return PerformActions();为了可维护性,你应该考虑移除返回语句是否会改变行为和代码,因为某个笨蛋会这样做(可能是我)。
还应该注意的是,使用else,代码在没有返回的情况下执行相同的操作,但是如果没有忽略返回,则会导致代码的行为不同。
https://stackoverflow.com/questions/3316305
复制相似问题