Reputation: 4850
I have some simple logic to check if the field is valid:
private boolean isValidIfRequired(Object value) {
return
(required && !isEmpty(value)) || !required;
}
it tells that the field is valid if it's either required and not empty or not required.
I don't like this required || !required part. Something with just required would be better. How do I simplify this method to make it more readable and simple?
Upvotes: 0
Views: 244
Reputation: 2387
The expected return of isValidIfRequired() is to return true.
So the exceptional cases must be put at the beginning as guardian clausules:
private boolean isValidIfRequired(Object value) {
if (required && empty(value)) //guardian clausule
return false;
return true;
}
for me the above code is more human-readable than using together expresions containing ANDs ORs and negations
Upvotes: 1
Reputation: 1074455
How 'bout:
private boolean isValidIfRequired(Object value) {
return !required || !isEmpty(value);
}
or (thanks, @Peter Lawrey)
private boolean isValidIfRequired(Object value) {
return !(required && isEmpty(value));
}
In either case, if required
is false
, the ||
or &&
expression will short-circuit and isEmpty
will never be called. If required
is true
, the second half of the ||
or &&
will be evaluated, calling isEmpty
and returning the (inverted) result of that call.
Upvotes: 6