java.lang.Boolean 非常适合处理三元逻辑,因为它可以恰好具有三种状态:Boolean.TRUE(是这样的)、Boolean.FALSE(不是这样的)和 null(我们不'知道是什么情况)。使用 switch 语句处理这个将是一个很好的设计,例如。在这个构造函数中:
public class URN {
private String value = null;
public URN (String value, Boolean mode){
switch (mode){
case TRUE:
if(!isValidURN(value))
throw new MalformedURLException("The string could not be parsed.");
this.value = value;
break;
case FALSE:
this.value = value.concat(checkByteFor(value));
break;
case null:
if(isValidURN(value))
this.value = value;
else
this.value = value.concat(checkByteFor(value));
break;
}
return;
}
不幸的是,Java 不允许这样做,并提示“无法打开 boolean 类型的值”。实现这个会导致混淆的控制流和不友好的代码:
public URN (String value, Boolean mode){
Boolean valid = null;
if (!Boolean.FALSE.equals(mode)){
valid = isValidURN(value);
if (Boolean.TRUE.equals(mode) && !valid)
throw new MalformedURLException("The string could not be parsed.");
if(Boolean.TRUE.equals(valid)) {
this.value = value;
return;
} }
this.value = value.concat(checkByteFor(value));
}
要以好的方式做到这一点需要实现一个枚举类(在现实生活中,它比这个例子中的更复杂,因为必须重写 .equals() 以便 Trinary.NULL.equals(null) 变为真)和转换:
private enum Trinary {TRUE, FALSE, NULL};
public URN (String value, Boolean toConvert, String x){
Trinary mode;
if(toConvert == null)
mode = Trinary.NULL;
else
mode = toConvert.equals(Boolean.TRUE) ? Trinary.TRUE : Trinary.FALSE;
switch (mode){
case TRUE:
if(!isValidURN(value)) throw new MalformedURLException("The string could not be parsed.");
this.value = value;
break;
case FALSE:
this.value = value.concat(checkByteFor(value));
break;
case NULL:
if(isValidURN(value))
this.value = value;
else
this.value = value.concat(checkByteFor(value));
break;
}
return;
}
在我看来,这是更好的解决方案,因为它的可读性更高,但是用于转换的原始方法代码大小的另一半很烦人,在现实生活中,您必须关心具有相同语义的两个不同的空值。有更好的方法吗?
最佳答案
像这样使用空对象来传达信息并不是最佳选择。请记住,您不能对空对象执行任何方法调用,这再次意味着如果您将来想要调用任何 .getClass、.equals、.compare 等,您将不得不重写代码。
您最好的选择绝对是使用枚举选项。
enum Ternary {TRUE,FALSE,UNKNOWN}
您可以进一步扩展该类以具有获取此类对象的方法,
public Ternary getByValue(Boolean o) {
if(o == null)
return UNKNOWN;
if(o)
return TRUE;
return FALSE;
}
关于java - 用 java.lang.Boolean 和 switch 做三元逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11897298/