java 异常 出口_java – 当一个语句被认为是单入口/单出口时,当它不是时?

一个出口点方法(单出口):

public int stringLength(String s) {

return s.length();

}

两个出口点方法:

public int stringLength(String s) {

if(s == null) {

return 0;

}

return s.length();

}

以下是Martin Fowler的书Refactoring的引用:

I often find I use Replace Nested Conditional with Guard Clauses when I’m working with a programmer who has been taught to have only one entry point and one exit point from a method. One entry point is enforced by modern languages, and one exit point is really not a useful rule. Clarity is the key principle: if the method is clearer with one exit point, use one exit point; otherwise don’t.

并举例说明上述陈述,比较这两种方法的代码:

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();

};

Nested conditional code often is written by programmers who are taught to have one exit point from a method. I’ve found that is a too simplistic rule. When I have no further interest in a method, I signal my lack of interest by getting out. Directing the reader to look at an empty else block only gets in the way of comprehension.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值