Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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"); } 
like image 471
zhuguowei Avatar asked Jan 04 '16 06:01

zhuguowei


People also ask

Can you use == for null in Java?

== 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.

How do I avoid multiple nulls in Java 8?

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.

How do you compare null in Java?

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 "!=


1 Answers

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.

like image 134
coolguy Avatar answered Nov 10 '22 01:11

coolguy