简体   繁体   中英

java ternary operator and lazy evaluation

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.

  • Readability. There are many situations in which in-lining if-then-else blocks can lead to improved readability of code.

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?

  • Efficiency. The difference in processing time between a logically equivalent inline if-then-else and a if-then-else block (if any) is almost certain to be vanishingly small and not important in real world applications. Therefore, you choose the structure that yields the best readability. In many cases, this is the ternary operator ... but not all cases.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM