使用函数式编程优化代码
生活随笔
收集整理的這篇文章主要介紹了
使用函数式编程优化代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原來的代碼邏輯:
@Component @Slf4j @JobHandler(value = "wechatSettlementHandler") public class WechatSettlementHandler extends IJobHandler {@Autowiredprivate SettlementBatchResource settlementBatchResource;@Overridepublic 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;}}問題:每次新增一個Job都要寫很多重復的代碼,所以希望將這部分公共代碼抽取出來。
代碼優化:
1)通過JobUtils類將公共代碼抽取
@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)原先的代碼邏輯變得很簡單
@Component @Slf4j @JobHandler(value = "wechatSettlementHandler") public class WechatSettlementHandler extends IJobHandler {@Autowiredprivate SettlementBatchResource settlementBatchResource;Consumer<Long> consumer = new Consumer<Long>() {@Overridepublic void accept(Long batchDate) {settlementBatchResource.weChatApproveBatch(batchDate);}};@Overridepublic ReturnT<String> execute(String s) throws Exception {JobUtils.doJob(consumer, s);return SUCCESS;} }使用lambda方式讓代碼更加簡潔:
@Component @Slf4j @JobHandler(value = "wechatSettlementHandler") public class WechatSettlementHandler extends IJobHandler {@Autowiredprivate SettlementBatchResource settlementBatchResource;Consumer<Long> consumer = batchDate -> settlementBatchResource.weChatApproveBatch(batchDate);@Overridepublic ReturnT<String> execute(String s) throws Exception {JobUtils.doJob(consumer, s);return SUCCESS;} }返回集合中的一條數據:
@Datapublic static class ResultBean {private String startDate;private String updatedDate;private String personScope;private List<ARContactListBean> aRContactList;} Optional.ofNullable(qygsxxhy.getResult()).map(e -> {//這邊要加一條判斷if(CollectionUtils.isEmpty(e.getARContactList())){return null;}return e.getARContactList().get(0);}).orElse(null)總結
以上是生活随笔為你收集整理的使用函数式编程优化代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中的string模块
- 下一篇: 房屋出租管理系统