I used spring boot to develop a shell project used to send email, e.g.
sendmail -from [email protected] -password foobar -subject "hello world" -to [email protected]
If the from
and password
arguments are missing, I use a default sender and password, e.g. [email protected]
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"); }
== and !=The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.
We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional . That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the hood.
Use "==" to check a variable's value. A "==" is used to check that the two values on either side are equal. If you set a variable to null with "=" then checking that the variable is equal to null would return true. variableName == null; You can also use "!=
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With