加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:01:04 所属栏目:Java 来源:网络整理
导读:我不确定我是否能很好地使用它,例如,Java中的if语句被称为单入口/单出口语句. 在条件为真的情况下,这被认为是单入口点,如果错误则认为是单出口点? if(someCondition) doSomething(); 什么是非(单项/单项退出)声明的例子? 解决方法 一个出口点方法(单出口)
我不确定我是否能很好地使用它,例如,Java中的if语句被称为单入口/单出口语句.
在条件为真的情况下,这被认为是单入口点,如果错误则认为是单出口点?

if(someCondition)
   doSomething();

什么是非(单项/单项退出)声明的例子?

解决方法

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

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读