zhuguowei zhuguowei - 5 years ago 233
Java Question

Java check two arguments either both not null or both null elegantly

I used spring boot to develop a shell poject used to send email, e.g.

sendmail -from foo@bar.com -password foobar -subject "hello world" -to aaa@bbb.com


If the
from
and
password
arguments are missing I use a default sender and password, e.g.
noreply@bar.com
and
123456
.

So if the user passes the
from
argument they must also pass the
password
argument and vice versa, that is to say either both are non-null, or both are null.

How to check this elegantly?

Now my way is

if ((from != null && password == null) || (from == null && password != null)) {
throw new RuntimeException("from and password either both exist or both not exist");
}

Answer Source

There is a way using ^ (XOR) operator:

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

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 message. You can't define what went wrong using single condition.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download