我有两个字符串的对象
public class Foo {
String firstCondition;
String secondCondition;
//...//
}
这些类型可能交替为空,但基于它们是否为空或不正确地希望委托(delegate)给特定方法。
我认为下面提出的解决方案非常丑陋。
if(firstCondition !=null && secondCondition!= null){
methodA();
}
if(firstCondition !=null && secondCondition == null){
methodB();
}
if(firstCondition ==null && secondCondition!= null){
methodC();
}
if(firstCondition ==null && secondCondition== null){
methodD();
}
我并不是在寻找现成的实现,但也许是在寻找某种模式在这种情况下该怎么做。
提前致谢!
最佳答案
实际上我对 4 个逻辑检查没有任何问题,你可能应该这样做。但是,我们可以使其更简洁,如下所示:
int flag1 = Objects.isNull(firstCondition) ? 0 : 1;
int flag2 = Objects.isNull(secondCondition) ? 0 : 1;
if (flag1 * flag2 == 1) {
methodA();
}
else if (flag1 + flag2 == 0) {
methodD();
}
else if (flag1 == 1 && flag2 == 0) {
methodB();
}
else {
methodC();
}
关于java - 创建请求并根据两个变量委托(delegate)它的最优雅的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60657680/