如何最小化下面的if else语句?还是我应该使用地图或开关?

时间:2018-11-26 09:18:38

标签: java if-statement switch-statement

public String identifyCellular(Long phone1, Long phone2, Long phone3) {

    String cellular = null;
    if (String.valueOf(phone2).trim().replaceAll("\\D", " ").equals("(07'\\d'{8})|(467'\\d'{8})")) {
        cellular = String.valueOf(phone2).trim().replaceAll("\\D", " ");
    } else if (String.valueOf(phone1).trim().replaceAll("\\D", " ").equals("(07'\\d'{8})|(467'\\d'{8})")) {
        cellular = String.valueOf(phone1).trim().replaceAll("\\D", " ");
    } else {
        cellular = String.valueOf(phone3).trim().replaceAll("\\D", " ");
    }
    return cellular;
}

2 个答案:

答案 0 :(得分:4)

这似乎很好,尤其是您仅使用1条implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.google.code.gson:gson:2.8.2' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.squareup.retrofit2:converter-scalars:2.3.0' 语句并且每个else-if条件评估都使用不同的变量。但是,您可以通过在if块之前修剪所有3个变量,重构正则表达式,并立即在if语句内返回,来使其变得更整洁。

此外,要与正则表达式匹配,请使用ifPattern.compile()获取匹配的组。然后使用Pattern.matcher()检查是否存在匹配项。

find()

答案 1 :(得分:0)

在阅读您的代码时,我不确定上述算法是否是一门艺术,还是解决该问题的真正需要。完成课程后,我建议您摆脱if语句

public String identifyCellular(Long... phones) {
    String matchedRegex = "(07'\\d'{8})|(467'\\d'{8})";
    Pattern pattern = Pattern.compile(matchedRegex);
    Optional<Long> first = Arrays.stream(phones)
        .filter(filterMatchingNumber(pattern))
        .findFirst();
    return String.valueOf(first.orElse(giveLastPhone(phones)));    
  }

  private Long giveLastPhone(Long[] phones) {
    return phones[phones.length - 1];
  }

  private Predicate<Long> filterMatchingNumber(Pattern r) {
    return phone -> r.matcher(getPhone1Trimmed(phone)).find();
  }

  private String getPhone1Trimmed(Long phone1) {
    return String.valueOf(phone1).trim().replaceAll("\\D", " ");
  }

在这种情况下,看起来不需要修剪和将非数字(\ D)替换为空格。我建议考虑跳过它

  final String matchedRegex = "(07'\\d'{8})|(467'\\d'{8})";
  final Pattern pattern = Pattern.compile(matchedRegex);

  public String identifyCellular(Long... phones) {
    Optional<Long> first = Arrays.stream(phones)
        .filter(filterMatchingNumber(pattern))
        .findFirst();
    return String.valueOf(first.orElse(giveLastPhone(phones)));
  }

  private Long giveLastPhone(Long[] phones) {
    return phones[phones.length - 1];
  }

  private Predicate<Long> filterMatchingNumber(Pattern pattern) {
    return phone -> pattern.matcher(phone.toString()).find();
}