gpt4 book ai didi

java - 什么时候说语句是单次进入/单次退出,什么时候不是?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:08 26 4
gpt4 key购买 nike

我不确定我是否理解得很好,例如Java中的if语句被称为单入口/单导出语句。如果它的条件为真,这是否被认为是它的单一入口点,如果条件为假,它是否被认为是它的单一导出点?

if(someCondition)
doSomething();

-(单次进入/单次退出)语句的示例是什么?

最佳答案

一个导出点法(single-exit):

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.

关于java - 什么时候说语句是单次进入/单次退出,什么时候不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17295315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com