[英]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. 显然,其中
t1
和t2
是等效的。
Is there a way, using operator precedence, to express the condition without using ternary operator and evaluating a
just one time? 有没有一种方法,使用运算符优先级,以表达不使用三元运算符和评估条件
a
只是一个时间?
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. 其中
execution.isActive()
是一项昂贵的操作。
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. 在现实生活中,如果a实际上是一个昂贵的通话的结果,我将其提取到一个变量中。
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? 我会说内联的if-then-else更具可读性,不是吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.