2016-06-14 5 views
0

2つの値を返す2つのメソッドがあります。メソッドはほとんど同じですので、私はそれらを単一メソッドに結合し、異なる値を返すように操作することを考えていましたが、それが有用であるかどうかは確かではありませんか?JAVAで2つのメソッドを結合するには?

この方法はシングルに変換できるのですか?私はisThisFruitPresentInTheListにメソッドの名前を変更する場合

private boolean getFirst(List<Apples> apples) { 

     boolean isOrange = false; 
     if (apples != null) { 
      for (Apples apple : apples) { 
       String type = apple.getFruit(); 
       boolean isApple = StringUtils.equalsIgnoreCase(type, ORANGE); 
       if (!isApple) { 
        isOrange = true; 
       } 
      } 
     } 
     return isOrange; 
    } 



private boolean getSecond(List<Apples> apples) { 

     boolean isAppletype = false; 
     if (apples != null) { 
      for (Apples apple : apples) { 
       String type = apple.getFruit(); 
       boolean isApple = StringUtils.equalsIgnoreCase(type, ORANGE); 
       if (isApple) { 
        isAppletype = true; 
       } 
      } 
     } 
     return isAppletype; 
    } 
+7

'ブールisApple = StringUtils.equalsIgnoreCase(タイプ、ORANGE)を次のように等価;'ビット奇妙です。タイプがオレンジならリンゴですか? – Tunaki

+2

とにかくリンゴのリストにはオレンジがどうですか?あなたはコードについてもっと教えていただけますか?これは[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)のように聞こえます。 – Tunaki

+0

クラスの名前は、とにかく 'アップル'と叫ぶ。それ以外の場合、オブジェクトに複数のリンゴが含まれているという錯覚が生じます。 –

答えて

1

はい、あなたがのために必ずそれが何のために、より汎用的なことができ、新しいものにそれらのメソッドをマージすることができます...

例えば、ご容赦下さい...

次に、メソッドにリストを渡すことができます。また、2番目のパラメータとして、探している果実があります。果物がリストに存在する場合はtrueを返し、そうでない場合はfalseを返します。そうでなければ...

例:

private boolean isThisFruitPresentInTheList(List<Apples> apples, String f) { 
     if (apples != null) { 
      for (Apples apple : apples) { 
       if (f.equalsIgnoreCase(apple.getFruit())) { 
        return true; 
       } 
      } 
     } 
     return false; 
    } 

、あなたがやってのようなメソッドを呼び出すことができます....

isThisFruitHere(List<Apples> apples, APPLES) 
isThisFruitHere(List<Apples> apples, ORANGES) 
4

あなたはこのためにストリームを使用することができます。

List<Apple> list = ...; 

// First method 
list.stream().anyMatch((e) -> !StringUtils.equalsIgnoreCase(e.getFruit(), ORANGE)); 
// Second method 
list.stream().anyMatch((e) -> StringUtils.equalsIgnoreCase(e.getFruit(), ORANGE)); 
0

private boolean containsType(List<Apples> apples, boolean orangeType) { 
    if (apples != null) { 
     for (Apples apple : apples) { 
      String type = apple.getFruit(); 
      boolean isOrange = StringUtils.equalsIgnoreCase(type, ORANGE); 
      if (orangeType == isOrange) 
       return true; 
     } 
    } 
    return false; 
} 

を考えます

あなたの方法は

  • getFirst(apples) =>containsType(apples, false)
  • getSecond(apples)
  • =>containsType(apples, true)
関連する問題