doumen5895 2015-12-17 07:23
浏览 11
已采纳

当控制结构中需要明确的“else”时?

What should one use? This, without else:

function($condition) {
    if($condition) {
        return true;
    }
    return false;
}

Or this, with an else:

function($condition) {
    if($condition) {
        return true;
    } else {
        return false;
    }
}

What are potential drawbacks?

Note: I understand that right solution for this very example would be

function($condition) {
    return (boolean)$condition;
}
  • 写回答

5条回答 默认 最新

  • douteng5673 2015-12-17 07:55
    关注

    In some cases it is possible to increase readability by setting "else" aside. Two examples below are eqiuvalent. Second produces less code, though it will suit only when we return values without complex calculations in that block, but again, we can utilize functions to make it usable.

    function($a, $b) {
        if($a) {
            if($a > $b) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    
    function($a, $b) {
        if($a) {
            if($a > $b) {
                return true;
            }
        }
        return false;
    }
    

    Note: if not speaking about general cases with more complex conditions assumption, this should fold to:

    function($a, $b) {
        return ($a and $a > $b);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数