-4
只是關於良好的編程習慣的一個簡短的問題,清潔Java編程,使用lambdas生成方法輸入參數是不是一個好主意?
除了表現,多少好/壞想法可能是這樣的? 我簡單地把問題簡化了一下,但是這樣的事情完全錯了嗎?
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,你可能會想要寫一個方法來代替。 – Moira
當然,*如果*你覺得在某些情況下它更乾淨。但是你給的例子非常糟糕。首先,它不能編譯。而且,你可以使用'?:' – ZhongYu
可讀性受損。方法名稱實際上是自我評論。一個空的lambda需要一個實際的評論,並沒有提供增長的簡易性。 – Compass