Java漏斗式顺序执行条件逻辑优化方案咨询
漏斗式条件逻辑的优化写法
你当前的多if写法重复度高,维护起来麻烦(比如新增方法还要额外加if判断),下面是几种更简洁易维护的优化方案:
方案一:循环遍历方法列表(最直观)
把所有要尝试的方法按顺序放进列表,循环调用直到拿到非空结果:
private List<String> filteredData() { // 按优先级顺序定义要尝试的方法 List<Supplier<List<String>>> methods = Arrays.asList( this::method1, this::method2, this::method3, this::method4, this::method5, this::method6, this::method7 ); for (Supplier<List<String>> method : methods) { List<String> result = method.get(); if (!CollectionUtils.isEmpty(result)) { return result; } } // 所有方法都返回空时,返回空列表 return new ArrayList<>(); }
新增方法只需要往methods列表里加,不用修改循环逻辑,非常方便。
方案二:Java 8+流式写法(更简洁)
用Stream的链式调用实现,代码更紧凑:
private List<String> filteredData() { return Stream.of( this::method1, this::method2, this::method3, this::method4, this::method5, this::method6, this::method7 ) .map(Supplier::get) .filter(list -> !CollectionUtils.isEmpty(list)) .findFirst() .orElse(new ArrayList<>()); }
逻辑和方案一一致,只是用流式API简化了循环和判断。
方案三:封装通用工具方法(多场景复用)
如果项目里多处有这种漏斗式逻辑,可以抽个通用方法复用:
// 通用工具:按顺序找第一个非空结果 private <T> T firstNonEmpty(List<Supplier<T>> suppliers, T defaultValue) { for (Supplier<T> supplier : suppliers) { T result = supplier.get(); if (result != null && !CollectionUtils.isEmpty((Collection<?>) result)) { return result; } } return defaultValue; } // 业务方法调用 private List<String> filteredData() { return firstNonEmpty(Arrays.asList( this::method1, this::method2, this::method3, this::method4, this::method5, this::method6, this::method7 ), new ArrayList<>()); }
优化后的优势
- 可维护性:增删方法只需要修改方法列表,不用重复写if判断
- 可读性:逻辑清晰,一眼就能看出是按顺序找第一个有效结果
- 复用性:通用工具方法可以在多个业务场景复用相同逻辑
内容的提问来源于stack exchange,提问作者Alagu Narayanan K
相关产品推荐
相关产品推荐

