I'm trying to simplify, once and for all, a common condition:
public static void main(String[] args)
{
boolean a = true;
boolean b = false;
boolean c = true;
boolean t1 = (a && b) || (!a && c);
boolean t2 = a ? b : c;
System.out.println(t1);
System.out.println(t2);
}
where, obviously, t1
and t2
are equivalent.
Is there a way, using operator precedence, to express the condition without using ternary operator and evaluating a
just one time?
Thanks
real world example:
if(execution.isActive() ? !Objects.equals(sourceStep, currentStep) : sourceStep != null)
{
throw new IllegalStateException("current action is not allowed to be executed");
}
where execution.isActive()
is an expensive operation.
For my taste, this is not readable at all... I have to stop and think, it's not immediate.
My question is about readability vs efficiency .
In real life, if a was actually the result of an expensive call, I'd just extract it to a variable.
change this:
boolean t1 = (expensiveCall() && b) || (!expensiveCall() && c);
to this:
boolean result = expensiveCall();
boolean t1 = (result && b) || (!result && c);
But apart from that: I don't see anything wrong with using the ternary operator.
If i want the code easier to read, I'd rather do like this:
private boolean isIllegalAction(execution,sourceStep,currentStep){
return execution.isActive() ? !Objects.equals(sourceStep, currentStep) : sourceStep != null;
}
if(isIllegalAction(...)){
//do something
}
My question is about readability vs efficiency
Very well.
Consider:
int result = (myObject.isCompleted())
? myObject.getStandardError()
: myObject.computeStandardError().getStandardError();
... compared to:
int result = 0;
if (myObject.isCompleted()) {
result = myObject.getStandardError();
}
else {
result = myObject.computeStandardError().getStandardError();
}
I would say the in-lined if-then-else is much more readable, wouldn't you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.