Check two arguments in Java, either both not null or both null elegantly

Well, it sounds like you're trying to check whether the "nullity" condition of the two is the same or not. You could use:

if ((from == null) != (password == null))
{
    ...
}

Or make it more explicit with helper variables:

boolean gotFrom = from != null;
boolean gotPassword = password != null;
if (gotFrom != gotPassword)
{
    ...
}

Put that functionality in a 2 argument method with the signature:

void assertBothNullOrBothNotNull(Object a, Object b) throws RuntimeException

This saves space in the actual method you are interested in and makes it more readable. There is nothing wrong with slightly verbose method names and there is nothing wrong with very short methods.


There is a way using the ^ (XOR) operator:

if (from == null ^ password == null) {
    // Use RuntimeException if you need to
    throw new IllegalArgumentException("message");
}

The if condition will be true if only one variable is null.

But I think usually it's better to use two if conditions with different exception messages. You can't define what went wrong using a single condition.

if ((from == null) && (password != null)) {
    throw new IllegalArgumentException("If from is null, password must be null");
}
if ((from != null) && (password == null)) {
    throw new IllegalArgumentException("If from is not null, password must not be null");
}

It is more readable and is much easier to understand, and it only takes a little extra typing.


Personally, I prefer readable to elegant.

if (from != null && password == null) {
    throw new RuntimeException("-from given without -password");
}
if (from == null && password != null) {
    throw new RuntimeException("-password given without -from");
}

Tags:

Java