我需要在具有许多其他条件的一组规则中编写具有许多条件(最多30个条件)的逻辑,并且该逻辑可以在所有条件之间或之后终止。

这是我在某些可能的情况下尝试的示例代码。这给了我结果,但是看起来并不好,并且在某种情况下的任何轻微失误都将永远需要跟踪。

到目前为止,我尝试过的是,取出常见条件并重构为某些方法。尝试创建具有条件和各种设置的接口(interface)将实现它。

如果您有任何设计建议,将对我有帮助。不需要详细的解决方案,但即使有提示也很好。

private Boolean RunCondition(Input input) {
    Boolean ret=false;
    //First if
    if(input.a.equals("v1")){
        //Somelogic1();
        //Second if
        if(input.b.equals("v2"))
            //Third if
            if(input.c >1)
                //Fourth if
                //Somelogic2();
                //Go fetch key Z1 from database and see if d matches.
                if(input.d.equals("Z1"))
                        System.out.println("Passed 1");
                    // Fourth Else
                    else{
                        System.out.println("Failed at fourth");
                    }

            //Third Else
            else{
                if(input.aa.equals("v2"))
                    System.out.println("Failed at third");
                }
        //Second Else
        else{
            if(input.bb.equals("v2"))
                System.out.println("Failed at second");
            }
    }
    //First Else
    else{
        if(input.cc.equals("v2"))
            System.out.println("Failed aat first");
        }

    return ret;
}

public class Input {
    String a;
    String b;
    int c;
    String d;
    String e;
    String aa;
    String bb;
    String cc;
    String dd;
    String ee;

}

最佳答案

流程很复杂,因为您拥有正常的流程,并且当某些值是异常值(例如无效)时,还有许多可能的异常流程。

这是使用 try/catch/finally 块进行处理的理想选择。

您的程序可以重写为以下内容:

private Boolean RunCondition(Input input) {
    Boolean ret=false;
    try {
        //First if
        if(!input.a.equals("v1")) {
            throw new ValidationException("Failed aat first");
        }
        //Somelogic1();

        //Second if
        if(!input.b.equals("v2")) {
            throw new ValidationException("Failed at second");
        }
        //Somelogic2()

        //Third if
        if(input.c<=1) {
            throw new ValidationException("Failed at third");
        }

        //Fourth if
        //Somelogic2();
        //Go fetch key Z1 from database and see if d matches.
        if(!input.d.equals("Z1")) {
            throw new ValidationException("Failed at fourth");
        }
        System.out.println("Passed 1");

    } catch (ValidationException e) {
            System.out.println(e.getMessage());
    }

    return ret;
}

您可以在其中定义自己的ValidationException(如下所示),也可以重用一些现有的标准异常,例如RuntimeException
class ValidationException extends RuntimeException {

    public ValidationException(String arg0) {
        super(arg0);
        // TODO Auto-generated constructor stub
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

}

您可以在下面阅读有关此内容的更多信息

https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

10-07 19:21
查看更多