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
  • What is a tree of ifs?
    – Maroun
    Jul 8, 2013 at 7:39
  • Please show us what have you tried ?
    – Makky
    Jul 8, 2013 at 7:39
  • 1
    If () { If () { if() { ... Jul 8, 2013 at 7:39
  • Conceptual questions are better suited for programmers.stackexchange.com
    – oberlies
    Mar 7, 2014 at 12:03

5 Answers 5

2

Use logical operators ..

As Simple as you can write to avoid if tree( in your words) and logical operators ..

if((condition1 || condition2) && condition3){ //this avoids tree with linear eq.
  //do some thing 
}
1

Apache Commons Validator or the Preconditions of Guava may help you to avoid writing if conditions.

1

You Could write a method such as below:

public static boolean isNull(Object... objArr) {
    for (Object o : objArr) {
         if ( obj == null)
            return true;
    }
    return false;
}
1
boolean pass = (f1 != null || (f1 != null && f2 != null);
if(pass){ /*do stuff*/ }
0

May be you need Hibernate Validator. You can google it for usage.

Not the answer you're looking for? Browse other questions tagged or ask your own question.