Optimizing code using functional programming

The original code logic:

@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {

    @Autowired
    private SettlementBatchResource settlementBatchResource;

    @Override
    public ReturnT<String> execute(String s) throws Exception {

        if(StringUtils.isEmpty(s)){
            log.info("执行时间: {}", DateTime.now());
            settlementBatchResource.weChatApproveBatch(DateTime.now().withTimeAtStartOfDay().getMillis());
            return SUCCESS;
        }
        try{
            Date date = new SimpleDateFormat("yyyyMMdd").parse(s);
            log.info("执行时间: {}", date);
            settlementBatchResource.weChatApproveBatch(date.getTime());
        }catch (Exception e){
            log.error("时间解析失败: {}", e);
        }
        return SUCCESS;
    }

}

Problem: Every time a new job is added, a lot of repetitive code needs to be written, so I hope to extract this part of the common code.

Code optimization:

1) Extract the common code through the JobUtils class

@Slf4j
public class JobUtils {

    public static void doJob(Consumer consumer, String s){

        if(StringUtils.isEmpty(s)){
            log.info("执行时间: {}", DateTime.now());
            long batchDate = DateTime.now().withTimeAtStartOfDay().getMillis();
            consumer.accept(batchDate);
        }
        try{
            Date date = new SimpleDateFormat("yyyyMMdd").parse(s);
            log.info("执行时间: {}", date);
            consumer.accept(date.getTime());
        }catch (Exception e){
            log.error("时间解析失败: {}", e);
        }
    }
}

2) The original code logic becomes very simple

@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {

    @Autowired
    private SettlementBatchResource settlementBatchResource;

    Consumer<Long> consumer = new Consumer<Long>() {
        @Override
        public void accept(Long batchDate) {
            settlementBatchResource.weChatApproveBatch(batchDate);
        }
    };

    @Override
    public ReturnT<String> execute(String s) throws Exception {

        JobUtils.doJob(consumer, s);
        return SUCCESS;
    }
}

Use the lambda method to make the code more concise:

@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {

    @Autowired
    private SettlementBatchResource settlementBatchResource;
    
    Consumer<Long> consumer = batchDate -> settlementBatchResource.weChatApproveBatch(batchDate);
    
    @Override
    public ReturnT<String> execute(String s) throws Exception {

        JobUtils.doJob(consumer, s);
        return SUCCESS;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324030115&siteId=291194637