【发布时间】:2010-12-28 01:47:19
【问题描述】:
有时条件会变得相当复杂,因此为了便于阅读,我通常将它们分开并给每个组件一个有意义的名称。然而,这会破坏短路评估,这可能会带来问题。我想出了一个包装方法,但在我看来它太冗长了。
谁能为此想出一个巧妙的解决方案?
有关我的意思的示例,请参见下面的代码:
public class BooleanEvaluator {
// problem: complex boolean expression, hard to read
public static void main1(String[] args) {
if (args != null && args.length == 2 && !args[0].equals(args[1])) {
System.out.println("Args are ok");
}
}
// solution: simplified by splitting up and using meaningful names
// problem: no short circuit evaluation
public static void main2(String[] args) {
boolean argsNotNull = args != null;
boolean argsLengthOk = args.length == 2;
boolean argsAreNotEqual = !args[0].equals(args[1]);
if (argsNotNull && argsLengthOk && argsAreNotEqual) {
System.out.println("Args are ok");
}
}
// solution: wrappers to delay the evaluation
// problem: verbose
public static void main3(final String[] args) {
abstract class BooleanExpression {
abstract boolean eval();
}
BooleanExpression argsNotNull = new BooleanExpression() {
boolean eval() {
return args != null;
}
};
BooleanExpression argsLengthIsOk = new BooleanExpression() {
boolean eval() {
return args.length == 2;
}
};
BooleanExpression argsAreNotEqual = new BooleanExpression() {
boolean eval() {
return !args[0].equals(args[1]);
}
};
if (argsNotNull.eval() && argsLengthIsOk.eval() && argsAreNotEqual.eval()) {
System.out.println("Args are ok");
}
}
}
对答案的回应:
感谢您的所有想法!目前已提交以下替代方案:
- 换行并添加 cmets
- 保持原样
- 提取方法
- 提前退货
- 嵌套/拆分 if's
换行并添加 cmets:
Eclipse 中的代码格式化程序(ctrl+shift+f)会撤消在条件中添加换行符。内联 cmets 对此有所帮助,但在每一行上留下的空间很小,并且可能导致难看的换行。然而,在简单的情况下,这可能就足够了。
保持原样:
我给出的示例条件非常简单,因此在这种情况下您可能不需要解决可读性问题。我在考虑条件更复杂的情况,例如:
private boolean targetFound(String target, List<String> items,
int position, int min, int max) {
return ((position >= min && position < max && ((position % 2 == 0 && items
.get(position).equals(target)) || (position % 2 == 1)
&& position > min && items.get(position - 1).equals(target)))
|| (position < min && items.get(0).equals(target)) || (position >= max && items
.get(items.size() - 1).equals(target)));
}
我不建议保持原样。
提取方法:
我考虑了提取方法,正如几个答案中所建议的那样。这样做的缺点是这些方法通常具有非常低的粒度,并且它们本身可能没有多大意义,因此它可能会使您的类变得混乱,例如:
private static boolean lengthOK(String[] args) {
return args.length == 2;
}
这真的不应该成为类级别的单独方法。您还必须将所有相关参数传递给每个方法。如果您创建一个单独的类纯粹用于评估非常复杂的条件,那么这可能是 IMO 的一个好的解决方案。
我尝试使用 BooleanExpression 方法实现的是逻辑保持本地化。请注意,即使 BooleanExpression 的声明也是本地的(我认为我以前从未遇到过本地类声明的用例!)。
提前退货:
早期退货解决方案似乎足够了,尽管我不赞成这个成语。另一种表示法:
public static boolean areArgsOk(String[] args) {
check_args: {
if (args == null) {
break check_args;
}
if (args.length != 2) {
break check_args;
}
if (args[0].equals(args[1])) {
break check_args;
}
return true;
}
return false;
}
我知道大多数人讨厌标签和中断,而且这种风格可能太不常见而无法被认为是可读的。
嵌套/拆分 if's:
它允许结合优化评估引入有意义的名称。一个缺点是可能会出现复杂的条件语句树
摊牌
因此,为了看看我最喜欢哪种方法,我将几个建议的解决方案应用于上面介绍的复杂 targetFound 示例。这是我的结果:
嵌套/拆分 if,具有有意义的名称 非常冗长,有意义的名称并没有真正帮助这里的可读性
private boolean targetFound1(String target, List<String> items,
int position, int min, int max) {
boolean result;
boolean inWindow = position >= min && position < max;
if (inWindow) {
boolean foundInEvenPosition = position % 2 == 0
&& items.get(position).equals(target);
if (foundInEvenPosition) {
result = true;
} else {
boolean foundInOddPosition = (position % 2 == 1)
&& position > min
&& items.get(position - 1).equals(target);
result = foundInOddPosition;
}
} else {
boolean beforeWindow = position < min;
if (beforeWindow) {
boolean matchesFirstItem = items.get(0).equals(target);
result = matchesFirstItem;
} else {
boolean afterWindow = position >= max;
if (afterWindow) {
boolean matchesLastItem = items.get(items.size() - 1)
.equals(target);
result = matchesLastItem;
} else {
result = false;
}
}
}
return result;
}
嵌套/拆分 if,使用 cmets 不那么冗长,但仍然难以阅读并且容易产生错误
private boolean targetFound2(String target, List<String> items,
int position, int min, int max) {
boolean result;
if ((position >= min && position < max)) { // in window
if ((position % 2 == 0 && items.get(position).equals(target))) {
// even position
result = true;
} else { // odd position
result = ((position % 2 == 1) && position > min && items.get(
position - 1).equals(target));
}
} else if ((position < min)) { // before window
result = items.get(0).equals(target);
} else if ((position >= max)) { // after window
result = items.get(items.size() - 1).equals(target);
} else {
result = false;
}
return result;
}
提前回报 更紧凑,但条件树仍然很复杂
private boolean targetFound3(String target, List<String> items,
int position, int min, int max) {
if ((position >= min && position < max)) { // in window
if ((position % 2 == 0 && items.get(position).equals(target))) {
return true; // even position
} else {
return (position % 2 == 1) && position > min && items.get(
position - 1).equals(target); // odd position
}
} else if ((position < min)) { // before window
return items.get(0).equals(target);
} else if ((position >= max)) { // after window
return items.get(items.size() - 1).equals(target);
} else {
return false;
}
}
提取方法 在您的班级中产生无意义的方法 参数传递很烦人
private boolean targetFound4(String target, List<String> items,
int position, int min, int max) {
return (foundInWindow(target, items, position, min, max)
|| foundBefore(target, items, position, min) || foundAfter(
target, items, position, max));
}
private boolean foundAfter(String target, List<String> items, int position,
int max) {
return (position >= max && items.get(items.size() - 1).equals(target));
}
private boolean foundBefore(String target, List<String> items,
int position, int min) {
return (position < min && items.get(0).equals(target));
}
private boolean foundInWindow(String target, List<String> items,
int position, int min, int max) {
return (position >= min && position < max && ((position % 2 == 0 && items
.get(position).equals(target)) || (position % 2 == 1)
&& position > min && items.get(position - 1).equals(target)));
}
重新审视 BooleanExpression 包装器 注意方法参数必须声明为final 对于这种复杂的情况,冗长是可以辩护的 IMO 如果他们同意的话,也许闭包会让这更容易(-
private boolean targetFound5(final String target, final List<String> items,
final int position, final int min, final int max) {
abstract class BooleanExpression {
abstract boolean eval();
}
BooleanExpression foundInWindow = new BooleanExpression() {
boolean eval() {
return position >= min && position < max
&& (foundAtEvenPosition() || foundAtOddPosition());
}
private boolean foundAtEvenPosition() {
return position % 2 == 0 && items.get(position).equals(target);
}
private boolean foundAtOddPosition() {
return position % 2 == 1 && position > min
&& items.get(position - 1).equals(target);
}
};
BooleanExpression foundBefore = new BooleanExpression() {
boolean eval() {
return position < min && items.get(0).equals(target);
}
};
BooleanExpression foundAfter = new BooleanExpression() {
boolean eval() {
return position >= max
&& items.get(items.size() - 1).equals(target);
}
};
return foundInWindow.eval() || foundBefore.eval() || foundAfter.eval();
}
我想这真的取决于情况(一如既往)。对于非常复杂的情况,包装方法可能是可辩护的,尽管它并不常见。
感谢您的所有意见!
编辑:事后诸葛亮。为复杂的逻辑创建一个特定的类可能会更好,例如:
import java.util.ArrayList;
import java.util.List;
public class IsTargetFoundExpression {
private final String target;
private final List<String> items;
private final int position;
private final int min;
private final int max;
public IsTargetFoundExpression(String target, List<String> items, int position, int min, int max) {
this.target = target;
this.items = new ArrayList(items);
this.position = position;
this.min = min;
this.max = max;
}
public boolean evaluate() {
return foundInWindow() || foundBefore() || foundAfter();
}
private boolean foundInWindow() {
return position >= min && position < max && (foundAtEvenPosition() || foundAtOddPosition());
}
private boolean foundAtEvenPosition() {
return position % 2 == 0 && items.get(position).equals(target);
}
private boolean foundAtOddPosition() {
return position % 2 == 1 && position > min && items.get(position - 1).equals(target);
}
private boolean foundBefore() {
return position < min && items.get(0).equals(target);
}
private boolean foundAfter() {
return position >= max && items.get(items.size() - 1).equals(target);
}
}
逻辑足够复杂,需要一个单独的类(和单元测试,耶!)。它将使使用此逻辑的代码更具可读性并促进重用,以防其他地方需要此逻辑。我认为这是一个不错的类,因为它确实有一个单一的职责,并且只有 final 字段。
【问题讨论】:
-
我喜欢您的第一个解决方案,但是通过正确命名变量,可能没有必要。您的第二个解决方案过于冗长 IMO。
标签: java