Reputation: 807
I look for a more elegant solution of this code:
var first = Optional.ofNullable(a);
var second = Optional.ofNullable(b);
if ((unit.isPresent() && value.isEmpty()) || (value.isPresent() &&
unit.isEmpty())) {
throw new ExpWhatever();
}
Conditions are:
Thanks for any ideas or help.
Upvotes: 2
Views: 627
Reputation: 328618
If you want both optionals to be either present or empty (i.e. they have the same "emptiness" state), you could use this:
if (unit.isPresent() != value.isPresent()) {
//throw an exception
}
Upvotes: 6
Reputation: 1500665
It sounds like it's an error for isPresent()
to be true for exactly one of them - so XOR works well:
if (unit.isPresent() ^ value.isPresent()) {
// Throw an exception
}
Upvotes: 7