2012-06-12 4 views
12

I statusが渡された場合にのみ、私はevent.statusプロパティをテストする次のような方法があります。私はそれは次のように行うことができると思っていたテストif文

def findEvent(String desc, String status = null, Collection events) { 
     return events.find { 
      it.description == desc && \\If status is not null: it.status == status 
     } 

     throw new Exception("Review Event Record Not Found: ${desc}") 
} 

を、それは動作していないようです:

def findEvent(String desc, String status = null, Collection events) { 
     return events.find { 
      it.description == desc && (status != null ?: {it.status == status}) 
     } 

     throw new Exception("Review Event Record Not Found: ${desc}") 
} 

これは何か方法がありますか?または、次のようなものに戻る必要がありますか。

if (status != null) { 
    return events.find { 
     it.description == desc && it.status == status 
    } 
} else if (status == null) { 
    return events.find { 
     it.description == desc 
    } 
} 

何らかのベストプラクティスがありますか?

答えて

21

私は表現がそれほど感覚的ではないと私は信じています。

エルヴィスは、「真実なら価値を使用し、そうでなければこの他のものを使用する」という意味です。

あなたの「他のもの」はクロージャーで、値はstatus != nullで、どちらもあなたの望むものではないようです。 statusの場合、Elvisはtrueと答えています。そうでない場合は、余分なレイヤーを取得します。

あなただけ使用することはできません理由:

(it.description == desc) && ((status == null) || (it.status == status)) 

その仕事をしなかった場合でも、あなたが必要とするすべての権利、適切な値を返すために閉鎖ですか? 2つの別々の呼び出しを作成する必要はなく、中間変数を使用するだけです。

+0

(it.description == desc)&&((status == null)||(it.status == status))は完璧に見えます。それは私がチャンスを得るときにうまく動作することを確認します。 確かにエルヴィスのオペレータに会ったのは今回が初めてのことなので、私は暗闇の中で遊んでいました。乾杯、デイブ –