栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

反转“ if”语句以减少嵌套

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

反转“ if”语句以减少嵌套

方法中间的返回不一定不好。如果它使代码的意图更加清晰,最好立即返回。例如:

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

在这种情况下,如果

_isDead
为true,我们可以立即退出该方法。最好这样构造它:

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

我已经从重构目录中选择了此代码。这种特定的重构称为:用Guard子句替换嵌套条件。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/470732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号