干净的java编程,使用lambdas生成方法输入参数是个坏主意吗?
只是一个关于良好编程实践的快速问题 撇开性能不谈,像这样的事情有多好/坏? 我把问题简单化了,以便让大家明白我的观点,但这样的事情完全错了吗干净的java编程,使用lambdas生成方法输入参数是个坏主意吗?,java,lambda,coding-style,readability,Java,Lambda,Coding Style,Readability,只是一个关于良好编程实践的快速问题 撇开性能不谈,像这样的事情有多好/坏? 我把问题简单化了,以便让大家明白我的观点,但这样的事情完全错了吗 public void methodWithInputString(String data) { // do something with data } public void methodThatCallsTheAbove() { methodWithInputString( // lambda with no inp
public void methodWithInputString(String data) {
// do something with data
}
public void methodThatCallsTheAbove() {
methodWithInputString(
// lambda with no input and a string as output
(() -> {
if (this.conditionIsTrue)
return "Condition is true";
else
return "Condition is false";
}).apply();
);
}
另一种选择是:
public void methodThatCallsTheAbove() {
if (this.conditionIsTrue)
methodWithInputString("Condition is true");
else
methodWithInputString("Condition is false");
}
我知道第二种方法是显而易见的/正确的,但在使用第一种方法使我的代码更干净的情况下,这仍然是一件荒谬的事情吗。
加上:避免在lambda中引用对象属性
我猜您试图展示的可编译版本如下所示:
public class Demo {
private static final Function<Boolean, String> GET_STRING_DEPENDING_ON_BOOLEAN = flagValue -> "Condition is ".concat(String.valueOf(flagValue));
private boolean conditionIsTrue;
public void methodWithInputString(final String data) {
// do something with data
}
public void methodThatCallsTheAbove() {
methodWithInputString(GET_STRING_DEPENDING_ON_BOOLEAN.apply(this.conditionIsTrue));
}
}
如果您发现自己在定义的同一个方法中使用lambda,那么您可能需要编写一个方法来代替它。当然,如果您觉得它在某些情况下更干净的话。但是你举的例子很糟糕。首先,它不能编译。而且,您可以使用
?:
可读性受到影响。方法名称实际上是自注释的。空的lambda需要一个实际的注释,并且不提供易于增长的功能。@ZhongYu是的,在我提供的示例中这样做毫无意义,第二个显然更具可读性。我的例子只是为了让大家明白我的观点。另外,我可以问一下为什么它不能编译吗?定义一个立即调用的lambda是一个毫无意义的想法。
methodWithInputString(GET_STRING_DEPENDING_ON_BOOLEAN.andThen(data -> data.concat("somethingelse")).apply(this.conditionIsTrue));