代码重构之函数式编程

近期接手的项目发现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等,可以多尝试使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值