0

I am looking for an elegant (basically, easy to read for other programmer) way to validate field values in constructor. Assuming that I have three fields that should be validated like following: only field 1 or field 1 and field 2 should not be null, not all of them. Is it something easier except of straight tree of if?

4

5 回答 5

2

使用逻辑运算符..

尽可能简单地编写以避免if树(用你的话)和逻辑运算符..

if((condition1 || condition2) && condition3){ //this avoids tree with linear eq.
  //do some thing 
}
于 2013-07-08T07:41:28.967 回答
1

Apache Commons ValidatorGuava 的前提条件可以帮助您避免编写 if 条件。

于 2013-07-08T07:40:02.063 回答
1

您可以编写如下方法:

public static boolean isNull(Object... objArr) {
    for (Object o : objArr) {
         if ( obj == null)
            return true;
    }
    return false;
}
于 2013-07-08T07:40:59.087 回答
1
boolean pass = (f1 != null || (f1 != null && f2 != null);
if(pass){ /*do stuff*/ }
于 2013-07-08T07:44:18.180 回答
0

可能你需要 Hibernate Validator。你可以google一下使用。

于 2013-07-08T07:46:39.477 回答