2017-02-09 44 views
-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"); 
} 

據我所知,第二是明顯的/正確的做法,但在使用的第一個的情況讓我的代碼清潔它仍然是一個荒謬的事情去做?

+0

如果你發現自己在它被定義的同樣的方法使用Lambda,你可能會想要寫一個方法來代替。 – Moira

+0

當然,*如果*你覺得在某些情況下它更乾淨。但是你給的例子非常糟糕。首先,它不能編譯。而且,你可以使用'?:' – ZhongYu

+0

可讀性受損。方法名稱實際上是自我評論。一個空的lambda需要一個實際的評論,並沒有提供增長的簡易性。 – Compass

回答

0

+1對安迪特納的評論。 :避免在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和鏈接別的東西。

例子:

methodWithInputString(GET_STRING_DEPENDING_ON_BOOLEAN.andThen(data -> data.concat("somethingelse")).apply(this.conditionIsTrue)); 
相關問題