近期接手的项目发现controller中的代码结构都是一样的,但是重复性代码太多。如下所示:
//产生实例对象
private ABusiness aService = new ABusiness();
private BBusiness bService = new BBusiness();
private CBusiness cService = new CBusiness();
@PostMapping("/A")
public void doA(AForm form, HttpServletRequest request, HttpServletResponse response) {
try{
//验签
verifyHeader(form,request);
//执行业务逻辑
String result = aService.doA(form);
getResponse(response, result);
} catch (Exception e) {
writeUnauthorizedResponse(e,response);
}
}
@PostMapping("/B")
public void doB(BForm form, HttpServletRequest request, HttpServletResponse response) {
try{
//验签
verifyHeader(form,request);
//执行业务逻辑
String result = bService.doB(form);
getResponse(response, result);
} catch (Exception e) {
writeUnauthorizedResponse(e,response);
}
}
@PostMapping("/C")
public void doC(CForm form, HttpServletRequest request, HttpServletResponse response) {
try{
//验签
verifyHeader(form,request);
//执行业务逻辑
String result = cService.doC(form);
getResponse(response, result);
} catch (Exception e) {
writeUnauthorizedResponse(e,response);
}
}
private void verifyHeader(Object form, HttpServletRequest request) {
//验签处理
}
private void getResponse(HttpServletResponse response, String result) {
//回复逻辑处理
}
private void writeUnauthorizedResponse(Exception e, HttpServletResponse response) {
//异常处理
}
}
类似如上的代码,每新增一个接口,开发同学都是直接复制,然后修改其中的业务处理那块代码如doC,doA 但是对于verifyHeader,getResponse,writeUnauthorizedResponse这些方法其实都是共用的,可以考虑抽出。
public void executeBusiness(Object form, Supplier<String> supplier) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
try{
//验签
verifyHeader(form,request);
//执行业务逻辑
getResponse(response, supplier.get());
} catch (Exception e) {
writeUnauthorizedResponse(e,response);
}
}
public void doA(AForm form) {
executeBusiness(form, () -> aService.doA(form));
}
public void doB(BForm form) {
executeBusiness(form, () -> bService.doB(form));
}
public void doC(CForm form) {
executeBusiness(form, () -> cService.doC(form));
}
这样代码看起来会简洁很多。JAVA8提供了许多函数式方法如Function,Predicate等,可以多尝试使用。