Service层业务逻辑校验代码重复问题的最优解决方案探讨
Service层业务逻辑校验的最优方案探讨
我正在探讨Service层中处理业务逻辑校验的最优方案。我的Service类中有多个方法需要执行相同的业务逻辑校验,若直接用if语句编写校验代码,IntelliJ会提示存在代码重复。
两种实现方式
方式一:直接在方法内编写校验逻辑
@Override public ReportDTO createCommentReport(Long id, ReportReasonDTO reasonDTO, String username) { log.info("Creating a report for comment with id {}", id); User userReporting = userRepository.findByUsername(username).get(); Comment commentFound = findCommentById(id); if (commentFound.getTopic().isClosed()) { log.error(EXCEPTION_OCCURRED, new TopicIsClosedException(TOPIC_WHERE_COMMENT_IS_CLOSED_EXCEPTION)); throw new TopicIsClosedException(TOPIC_WHERE_COMMENT_IS_CLOSED_EXCEPTION); } String reason = reasonDTO.reason(); Report reportBuilt = ReportMapper.buildReport(userReporting, reason, commentFound); reportRepository.save(reportBuilt); log.info("Report created"); return ReportMapper.buildReportTopicDTO(reportBuilt); }
方式二:将校验逻辑抽离到独立校验类
@Override public ReportDTO createCommentReport(Long id, ReportReasonDTO reasonDTO, String username) { log.info("Creating a report for comment with id {}", id); User userReporting = userRepository.findByUsername(username).get(); Comment commentFound = findCommentById(id); topicValidator.validateTopicClosed(commentFound.getTopic()); String reason = reasonDTO.reason(); Report reportBuilt = ReportMapper.buildReport(userReporting, reason, commentFound); reportRepository.save(reportBuilt); log.info("Report created"); return ReportMapper.buildReportTopicDTO(reportBuilt); }
目前考虑的方案
- 在Service方法中重复编写校验代码
- 创建独立的校验类
- 在Service类中新增校验方法(但我认为这会违反单一职责原则SRP)
内容的提问来源于stack exchange,提问作者huga721
相关产品推荐
相关产品推荐

