Is it correct to use multiple OR conditions in one if statement, what are alternatives?

I would like to know which way is more suitable and efficient in achieving something like: checking if text was entered in a field

if(text1.equals("") || text2.equals("") || text3.equals("") || text4.equals("")) {
  //Do Stuff
}

I can see how this gets messy quickly with more than 2 fields, and would like to know if this is a correct way to do this, or do alternatives exist?


You can do something like this:

if (Arrays.asList(text1, text2, etc).contains(""))

But a better solution would depend on the context.

Note however that this is a little slower than your current code. If you don't execute that test a bazillion times a second, though, it should not matter.


EDIT since it has been learned in the comments that strings with only spaces should also satisfy the condition... Here goes:

private static final Pattern PATTERN = Pattern.compile("\\s*");

private static boolean emptyOrSpacesOnly(final String... strings)
{
    for (final String s: strings)
        if (PATTERN.matcher(s).matches())
            return true;
    return false;
}

Then, in code:

if (emptyOrSpacesOnly(text1, text2, etc))

fge's solution is certainly clever and reduces the lines of code. However, I feel some of the meaning is lost when glancing at that snippet of code.

I would encourage you to embrace readable code, even if it's slightly more verbose. My solution would be to test these preconditions before beginning a method. If the precondition fails, throw an exception.

Either write your own validation methods or use something like Apache Commons Lang Validate class. Then your code would look something like:

Validate.notEmpty(text1, "error message");
Validate.notEmpty(text2, "error message");
Validate.notEmpty(text3, "error message");
Validate.notEmpty(text4, "error message");

// This line is only reached if all fields are non-empty

I think this is easy to read, which is half the battle won.