我有一个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层,有两种方法,一种是showForm()
显示表单供用户输入;另一种是显示表单供用户输入。另一种是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 的函数式解决方案是受欢迎的。
谢谢。