反转"若"语句来减少嵌套 [英] Invert "if" statement to reduce nesting

查看:863
本文介绍了反转"若"语句来减少嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我跑 ReSharper的我的code,例如:

When I ran ReSharper on my code, for example:

    if (some condition)
    {
        Some code...            
    }

ReSharper的给了我上述警告(反转if语句,以减少嵌套),并提出以下更正:

ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:

   if (!some condition) return;
   Some code...

我想明白为什么那最好不过。我始终认为,在方法问题的中间使用回归,有点像转到。

I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".

推荐答案

在方法中间的返回不一定是坏事。它可能会更好,如果它使code更清晰的意图,立即返回。例如:

A return in the middle of the method is not necessarily bad. It might be better to return immediately if it makes the intent of the code clearer. For example:

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
            else result = normalPayAmount();
        };
    }
     return result;
};

在此情况下,如果 _isDead 是真实的,马上就可以摆脱的方法。它可能会更好,而不是这种方式构建的:

In this case, if _isDead is true, we can immediately get out of the method. It might be better to structure it this way instead:

double getPayAmount() {
    if (_isDead)      return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired)   return retiredAmount();

    return normalPayAmount();
};   

我从重构目录选择这个code。这种特殊的重构称为:与保护条款替换嵌套条件

I've picked this code from the refactoring catalog. This specific refactoring is called: Replace Nested Conditional with Guard Clauses.

这篇关于反转"若"语句来减少嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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