2

私はServiceとを持っていControllerます。

サービス内の各メソッドの前提条件。例:

  public void doSomething(Parameter para1 , Parameter para2 ...) {
    if ( something wrong ) {
      throw new RuntimeException1();
    }
    if ( another thing wrong ) {
      throw new RuntimeException2();
    }
    // continue do something 
  }

また、Controller レイヤーには 2 つの方法があります。1 つはshowForm()、ユーザーが入力するフォームを表示する方法です。もう 1 つはdoApplyForm()、フォームを受け入れて下層を呼び出すものService.doSomething()です。

以下は疑似コードです (いくつかのBindingResult,attr.addFlashAttributeコードを削除しました) :

  @Injected Service service;

  public String showForm() {
    if ( something wrong ) {
      throw new RuntimeException1();
    }
    if ( another thing wrong ) {
      throw new RuntimeException2();
    }
    return "showForm";
  }

  public String doApplyForm(@Validated Form form) {
    try {
      service.doSomething(para1 , para2 ...);
      return "redirect:/";
    } catch (Exception e) {
      // error handling 
      return "redirect:/error";
    }
  }

うまく機能しますが、満足していません。中には異臭が漂います。

問題は、showForm()と同じ前提条件を共有する にありController.doSomething()ます。

Service.doSomething()今後別の前提条件を追加する場合Controller.showForm()は、対応する変更を行う必要があります。

このような悪臭をなくすためのデザインパターンやフレームワークはあるのだろうか?

Java8 の機能的なソリューションは大歓迎です。

ありがとう。

4

2 に答える 2

1

と呼ばれる util クラスを定義し、Preconditionsすべての検証ロジックをそこに移動できます。これは一般的なパターンであり、それを利用するフレームワークが多数あります。たとえば、Guava: Preconditions docs .

少なくともこのようif (condition) throw new exceptionにカプセル化され、管理が容易になります。

于 2015-11-11T12:22:55.687 に答える
1

サービス リクエストのパラメータ オブジェクトを導入し、検証ロジックをリクエスト オブジェクトに入れます。例えば

public class DoSomethingRequest {

   private Parameter param1;
   private Parameter param2;


   public void validate(){
       if ( something wrong ) {
           throw new RuntimeException1();
       }
       if ( another thing wrong ) {
           throw new RuntimeException2();
       }
   }

}

あなたのサービスはより簡単になります

public void doSomething(DoSomethingRequest request) {
    request.validate();
}

だからコントローラー

public String showForm() {
    DoSomethingRequest request = ... // obtained somehow
    request.validate();
    // ...
    return "showForm";
}

これにより、サービス メソッドの前提条件がオブジェクトにカプセル化されます。

于 2015-11-12T10:49:56.020 に答える