Do not Nest you Code
in developCo-De with 0 comment

Do not Nest you Code

in developCo-De with 0 comment

Nest is a Problem

  1. Nest Code is hard to understand
  2. 代码的圈复杂度(Cyclomatic complexity)是衡量质量的标准之一。
  3. 复杂度越高,理解越困难,测试越困难,维护越困难,出错的概率越高,事故风险越高

How to improve

Extraction 抽取

Inversion 判断反转

  public int nestCase(String numbers) {
    if (org.springframework.util.StringUtils.hasText(numbers)) {
      String[] inputs = numbers.split(",");
      int total = 0;
      for (String s : inputs) {
        try {
          int input = Integer.parseInt(s);
          total = total + input;
        } catch (Exception e) {
          log.error("Input is not a valid number");
          return 0;
        }
      }
      return total;
    } else {
      log.error("Input can not be null");
      return 0;
    }
  public int nestCase1(String numbers) {
    // Check One 
    if (!org.springframework.util.StringUtils.hasText(numbers)) {
      log.error("Input can not be null");
      return 0;
    }
    // Check Tow
    if (!Pattern.matches("^[1-9,]*$", numbers)) {
      log.error("Input is not a valid number");
      return 0;
    }
    String[] inputs = numbers.split(",");
    // Use Functions
    return Arrays.stream(inputs).mapToInt(Integer::parseInt).sum();
  }
Comments are closed.