Java 代码优化:使用函数式接口提取公共方法

假设你有一个类中包含两个类似的方法,它们唯一的区别在于获取的属性不同,例如:

private String getEmpCode(final boolean examinerFlag,
                          final IdentityStatsDTO identityStats) {
    return examinerFlag ? identityStats.getExaminerEmpCode() : identityStats.getAppraiseeEmpCode();
}

private String getIdentity(final boolean examinerFlag,
                          final IdentityStatsDTO identityStats) {
    return examinerFlag ? identityStats.getExaminerIdentity() : identityStats.getAppraiseeIdentity();
}

可以将这两个方法提取为一个公共方法,如下:

private String getValue(final boolean examinerFlag,
                          final IdentityStatsDTO identityStats,
                          final Function<IdentityStatsDTO, String> valueGetter) {
    return examinerFlag ? valueGetter.apply(identityStats) : identityStats.getAppraiseeEmpCode();
}

// 使用示例
String empCode = getValue(examinerFlag, identityStats, IdentityStatsDTO::getEmpCode);
String identity = getValue(examinerFlag, identityStats, IdentityStatsDTO::getIdentity);

这里使用了 Java 的函数式接口 Function,通过 valueGetter 参数来获取属性的值。在调用时,可以传入一个方法引用来指定要获取的属性。

这种方法的优点:

  • 减少重复代码: 将重复的逻辑提取到一个公共方法中,减少了代码冗余。
  • 提高代码可读性: 代码结构更加清晰,易于理解和维护。
  • 更灵活: 可以根据需要传入不同的 valueGetter 方法引用来获取不同的属性。

通过使用函数式接口,可以有效地优化代码结构,提高代码质量。

Java 代码优化:使用函数式接口提取公共方法

原文地址: https://www.cveoy.top/t/topic/Gu9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录