如何优化Java代码中的双重if语句?新手开发者求助
Java代码中两个if语句的优化方案
优化后的代码
@Override @Transactional public void deleteItem(final ConfigurationType type, final long itemId, final boolean force) { this.applicationNameUtils.throwOnInvalidApplication(type.getApplication()); final ConfigurationItemModel item = this.configurationItemRepository.findByApplicationAndTopicAndId(type.getApplication(), type.getTopic(), itemId) .orElseThrow(() -> new ResourceNotFoundException(itemId, "Configuration Item")); // 拦截不允许删除的场景 if (Boolean.TRUE.equals(item.getContentModificationOnly()) && !force) { throw new ContentModificationOnlyException("Configuration Item cannot be deleted"); } // 强制删除时执行清理与删除操作 if (force) { this.assignmentService.deleteAssignmentsByItem(item); this.configurationInstanceRepository.deleteByItem(item); this.configurationItemRepository.deleteById(itemId); } }
改写思路与原因
移除完全冗余的条件判断
原第二个if中的(Boolean.TRUE.equals(item.getContentModificationOnly()) || Boolean.FALSE.equals(item.getContentModificationOnly()))完全没有意义——布尔类型只有true和false两种取值,这个表达式永远为true,直接去掉后不影响逻辑,还能减少不必要的计算。简化条件表达式
Boolean.FALSE.equals(force)可以直接写成!force,因为force是基本类型boolean,不存在空指针风险,这样写更简洁易读。逻辑分层更清晰
先判断禁止删除的异常场景(抛异常终止方法),再处理允许删除的正常场景(force为true时执行删除逻辑),代码逻辑一目了然,后续维护时更容易理解每一段的作用。
关于if-else结构的说明
你可以将两个语句合并为if-else结构,但其实没有必要——因为第一个if中抛出异常后,方法会直接终止,不会执行后续代码。如果硬要写成if-else,代码如下:
if (Boolean.TRUE.equals(item.getContentModificationOnly()) && !force) { throw new ContentModificationOnlyException("Configuration Item cannot be deleted"); } else if (force) { this.assignmentService.deleteAssignmentsByItem(item); this.configurationInstanceRepository.deleteByItem(item); this.configurationItemRepository.deleteById(itemId); }
这种写法和分开的if效果完全一致,但分开写的方式更符合"先拦截异常,再执行正常逻辑"的代码习惯,可读性反而更好。
内容的提问来源于stack exchange,提问作者emung
相关产品推荐
相关产品推荐

