关于代码的重构、优化,有很多技巧,我在这里记录下我遇到的问题
- 可以采用lambda function,来解决方法内重复出现的代码,让逻辑更清晰
// old
TechnicalApproverComment comment1 = new TechnicalApproverComment();
comment1.setCreateByName(ApproverName1.getRealName());
comment1.setCreateBy(ApproverName1.getPersonnelInfoCode());
TechnicalApproverComment comment2 = new TechnicalApproverComment();
comment2.setCreateByName(ApproverName2.getRealName());
comment2.setCreateBy(ApproverName2.getPersonnelInfoCode());
TechnicalApproverComment comment3 = new TechnicalApproverComment();
comment3.setCreateByName(ApproverName3.getRealName());
comment3.setCreateBy(ApproverName3.getPersonnelInfoCode());
TechnicalApproverComment sealPersonComment = new TechnicalApproverComment();
sealPersonComment.setCreateByName(sealPerson.getRealName());
sealPersonComment.setCreateBy(sealPerson.getPersonnelInfoCode());
// new
Function<BasePersonnelInfoVO, TechnicalApproverComment> generateCommentDataFunc = (BasePersonnelInfoVO person) -> {
TechnicalApproverComment comment = new TechnicalApproverComment();
comment.setCreateByName(person.getRealName());
comment.setCreateBy(person.getPersonnelInfoCode());
return comment;
};
TechnicalApproverComment comment1 = generateCommentDataFunc.apply(ApproverName1);
TechnicalApproverComment comment2 = generateCommentDataFunc.apply(ApproverName2);
TechnicalApproverComment comment3 = generateCommentDataFunc.apply(ApproverName3);
TechnicalApproverComment sealPersonComment = generateCommentDataFunc.apply(sealPerson);
// 通过上面的优化,可以让人一目了然,同一段代码执行了4次,干了相同的工作,只是参数不同