在检查事件时,使用switch或if代码块是常见的做法。当它被简化时,可以是清晰易懂的代码,但仍然似乎比必要的行数更多,并且可以使用lambda表达式进行简化。
if代码块:
if(action == ACTION_1){
doAction1();
} else if(action == ACTION_2){
doAction2();
} else {
doDefaultAction();
}
带有 switch 的代码块:
switch(action){
case ACTION_1:
doAction1();
break;
case ACTION_2:
doAction2();
break;
default:
doDefaultAction();
}
使用以下实用类
With
来使用 Lambda 表达式的块:with(action)
.when(ACTION_1, this::doAction1)
.when(ACTION_2, this::doAction2)
.byDefault(this::doDefaultAction)
使用lambda的代码量更少,但问题是:它比其他方法更易读吗?更易于维护?在性能方面,lambda是最差的,但对于性能不重要的情况下,使用lambda版本比开关/ if块更短。
那么,你怎么看?也许有一种Kotlin方法比这更短,我只专注于Java,我喜欢Kotlin,但它的编译速度对我的项目来说仍然太慢了。
当块必须返回特定值时,可以使用类似的实用程序类。
FYI,用于lambda的类在这里,我没有检查错误,只是为了这个示例快速制作的:
public class With<T> {
private final T id;
private boolean actionFound;
private With(T id) {
this.id = id;
}
public static <T> With<T> with(T id) {
return new With<>(id);
}
public With<T> when(T expectedId, Action action) {
if (!actionFound && id == expectedId) {
actionFound = true;
action.execute();
}
return this;
}
public void byDefault(Action action) {
if (!actionFound) {
action.execute();
}
}
@FunctionalInterface
interface Action {
void execute();
}
}
==
比较不好,但是它与switch
做的事情相同,因此在这种情况下比较应该不是问题。 - Ignacio Tomas CrespoArrays.sort
或Collections.sort
时,Java不使用冒泡排序... 并非所有正确的算法都是相等的。 - Andy Turner-128 < int < 127
也不会按照您的期望工作。别忘了switch
支持String
。 - Boris the Spiderif_acmpne
指令进行的,但必须确保它使用缓存来处理频繁出现的值。谢谢! - Ignacio Tomas Crespo