公用代码片码抽取需要不断的强化代码复用意识
抽取前:
public void handleContext(UniterChineseSelectRequest context) {
IPage<UniterChinese> page = context.buildPage();
LambdaQueryWrapper<UniterChinese> query= context.buildQuery();
IPage<UniterChinese> uniterChinesePage = uniterChineseMapper.selectPage(page,query);
List<UniterChinese> uniterChineses = uniterChinesePage.getRecords();
List<UniterChineseListVo> uniterChineseVos = list2list(uniterChineses, UniterChineseListVo::new);
context.setResult(uniterChineseVos);
context.setTotal(uniterChinesePage.getTotal());
}
抽取后:
public void handleContext(UniterChineseSelectRequest context) {
IPage<UniterChinese> pageResult =
uniterChineseMapper.selectPage(context.buildPage(), context.buildQuery());
context.setPageResult(pageResult,UniterChineseListVo::new);
}
抽取的公用代码片断:
public <T, E> void setPageResult(IPage<T> pageResult, Function<T, E> fun) {
List<T> ts = pageResult.getRecords();
List<E> es = ZYListUtils.list2list(ts, fun);
this.setResult(es);
this.setTotal(pageResult.getTotal());
}
public static <O, T> List<T> list2list(List<O> os, Function<O, ? extends T> target, boolean needClearRepeat) {
List<T> ts = new ArrayList<>();
if (null == os || os.size() == 0) {
return ts;
}
os.forEach(o -> {
T apply = target.apply(o);
if (ZYStrUtils.isNotNull(apply)) {
if (needClearRepeat) {
if (!ts.contains(apply)) {
ts.add(apply);
}
} else {
ts.add(apply);
}
}
});
return ts;
}