java - 创建请求并根据两个变量委托(delegate)它的最优雅的方式

标签 java

我有两个字符串的对象

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/

相关文章:

java - 文本 "<? >"有什么特殊含义吗?

java - GOOGLE_APPLICATION_CREDENTIALS 身份验证无法在远程 ubuntu 机器上运行

java - 如何在Eclipse中获取AWT?

java - 如何衡量JAVA MetaSpace?

java - GWT 2.6 和 jdk 1.6 出现 UnsupportedClassVersionError

java - 设置System.setOut();到命令提示符

java - 处理MaxUploadSizeExceededException : Ajax File Uploading

java - Apache 状态 500 : Null pointer exception

java - Http 客户端由于某种原因挂起

java - WTRN0062E : An illegal attempt to use multiple resources that have only one-phase capability has occurred within a global transaction