Java 在控制器和服务之间共享相同的方法前置逻辑?

Java 在控制器和服务之间共享相同的方法前置逻辑?,java,spring,spring-mvc,design-patterns,preconditions,Java,Spring,Spring Mvc,Design Patterns,Preconditions,我有一个服务和一个控制器 服务中的每个方法都有其先决条件,例如: public void doSomething(Parameter para1 , Parameter para2 ...) { if ( something wrong ) { throw new RuntimeException1(); } if ( another thing wrong ) { throw new RuntimeException2(); }

我有一个
服务
和一个
控制器

服务中的每个方法都有其先决条件,例如:

  public void doSomething(Parameter para1 , Parameter para2 ...) {
    if ( something wrong ) {
      throw new RuntimeException1();
    }
    if ( another thing wrong ) {
      throw new RuntimeException2();
    }
    // continue do something 
  }
在控制器层,有两种方法,一种是
showForm()
,它显示表单供用户输入;另一个是
doApplyForm()
,它接受表单并调用底层
服务.doSomething()

以下是伪代码(我消除了一些
BindingResult
attr.addFlashAttribute
代码):

它工作得很好,但我不满意。里面有难闻的气味

问题在于
showForm()
,它与
Controller.doSomething()
具有相同的先决条件

如果
Service.doSomething()
将来添加另一个前提条件,
Controller.showForm()
必须进行相应的更改

我想知道是否有任何设计模式或框架可以消除这种异味

欢迎使用Java8的功能解决方案


谢谢。

您可以定义一个名为
Premissions
的util类,并将所有验证逻辑移到那里。这是一种常见的模式,有许多框架使用它。例如,番石榴:


至少像这样,您的
如果(条件)抛出新异常
将被封装并更易于管理。

为服务请求引入参数对象,并将验证逻辑放入请求对象中。例如

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";
}
这将服务方法的前提条件封装在对象中

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