I used spring boot to develop a shell project 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 do I 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");
}
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)
{
...
}
See more on this question at Stackoverflow