0

我的应用程序有一项服务,其中 3 个方法执行一些验证,并根据返回的结果引发不同的异常。

  if (!check1stCondition() {
    throw new ValidationException(message1);
  }

  if (!check2ndCondition)
    throw new ValidationException(message2);

  if (!check3rdCondition)
    throw new ValidationException(message3);
}

我如何重新格式化此代码以便将来可以维护?将来可以执行新的检查。

4

4 回答 4

4

您可以定义一个接口,Checker提供一个check在这种情况下引发异常的方法。您的代码可以更改为类似

public interface Checker {
    void check() throws ValidationException;
}

public class YourClass {
   private List<Checker> checkers; // initialize through (dependency inhecjetd?) constructor parameter or by simply enumerating checker in the constructor; I personally prefer the first way

   public void yourMethod() {
     for(Checkech checker : checkers) {
        checker.check();
     }
   }
}

您显然可以向check方法添加参数以提供要验证的数据...

更新

如果您确实可以控制条件检查实现,则可以切换到类似的内容(请参阅@Alberto Venturini 的评论):

public interface Checker {
    boolean check();

    String message();
}

public class YourClass {
   private List<Checker> checkers; // initialize through (dependency inhecjetd?) constructor parameter or by simply enumerating checker in the constructor; I personally prefer the first way

   public void yourMethod() {
     for(Checkech checker : checkers) {
        if(!checker.check()) {
            throw new ValidationException(checker.message());
        }        
     }
   }
}

您可以使用维护检查条件和相应错误消息之间关联Checker的变量来实现第一个定义的类似解决方案,但我绝对更喜欢@Alberto Venturini 提出的多态方法。Map<String, Checker>

我希望这种方法可以帮助您将代码移向更加开放封闭的解决方案!

于 2019-02-11T11:38:37.617 回答
0

我看到你有 3 个不同的条件和 3 个不同的消息。值得使用像Guava 这样的前置条件或自己编写。

你的代码会喜欢

checkState(check1stCondition(), message1);
checkState(check2stCondition(), message2);

你不会完全减少if's。但至少你增加了可读性。

于 2019-02-11T11:58:26.527 回答
0

有一种方法接近 OOP。注意:我不坚持,只是展示一个替代方案。

首先,您可以为每个条件创建一个新类。假设您对某些数据进行检查,它将如下所示:

interface Condition {
    CustomData checkedData();
}

public class Condition1 implements Condition {
    private CustomData data;

    public Condition1(CustomData data) {
        this.data = data;
    }

    public Condition1(Condition condition) {
        this.data = condition.checkedData();
    }

    public CustomData checkedData() {
        // do condition checking here and return CustomData if it's ok
        // throw exception otherwise
    }
}

然后您可以将每个包装Condition在另一个中:

CustomData data = new Condition1(
                      new Condition2(
                          new Condition3(YOUR_DATA))).checkedData();

您现在可以确定您的数据已经过检查并准备好进行进一步的工作。

我相信它很容易维护。如果你需要一些新的检查,只需像上面一样添加一些小类,然后将你的数据包装在另一个Condition. 如果你想改变一些条件,你不必在通用代码中寻找它。你有单独的课程。

于 2019-02-11T13:13:00.297 回答
0

您可以尝试使用多态性来减少 if 语句并提高可维护性。

只需使用这样的界面

public interface Example {

void check() throws ValidationException;
}

并实施不同的行为。

于 2019-02-11T12:16:44.987 回答