gpt4 book ai didi

java - 没有 else 的条件三元

转载 作者:行者123 更新时间:2023-12-02 03:26:46 24 4
gpt4 key购买 nike

我读过类似的问题,并了解到不可能使用三元运算来代替 if 语句,因为它没有 else 语句。因为,if-without else 语句是二进制而不是三元。我的问题是更多的最佳实践。

在我的代码中,有很多这样的代码片段

  if( calculation < 1 ){
calculation= 0;
}

我想用 tenary 来缩短这些。使用以下内容更改这些语句是否是一个好习惯?

calculation = calculation < 1 ? 0 : calculation;

最佳答案

您可以创建一个(或多个)类来创建流畅的 API。这样你的行将是:

calculationTo = replace(calculationTo).with(0).when(calculationTo < 1)

在我看来,它读起来并不比标准 if 语句好多少,但它也取决于您所拥有的条件。

实现示例:

public class Replacer<T> {

private final T value;
private T replacementValue;

private Replacer(T value) {
this.value = value;
}

public static <V> Replacer<V> replace(V value) {
return new Replacer<V>(value);
}

public Replacer<T> with (T replacementValue) {
this.replacementValue = replacementValue;
return this;
}

public T when(boolean condition) {
if (condition) {
return replacementValue;
} else {
return value;
}
}

}
<小时/>
import static somepackage.Replacer.replace;

public class Main {

public static void main(String[] args) {
int calculationTo = 3;

calculationTo = replace(calculationTo).with(0).when(calculationTo < 1);
}

}

您可以扩展它或将条件设置为函数,以便它可以与 lambda 等一起使用。我还会使方法 with 返回不同类的对象(例如 ReplacerWithValue ),因此在一个链中调用 with 两次会导致编译错误。

关于java - 没有 else 的条件三元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com