"Reconstruction": Consolidate Conditional Expression

Let’s focus on: Logical AND, multi-level if nesting occurs

In actual development, the AND gate should be the easiest and the most optimized.

  • The merged condition code will state "There is actually only one condition check, but there are multiple parallel conditions to be checked, making the purpose of this check clearer. Of course, the pre-merged and merged codes have the same effect, but The message conveyed by the original code is "here are some independent condition tests, they just happen to happen at the same time"
  • This refactoring often sets the stage for using the Extract function. Distilling the check condition into a separate function is very useful for clarifying the meaning of the code, because it replaces the statement describing "what" with "why".

Case 1: Logical OR

public int disabilityAmount(Employee anEmployee) {
  if (anEmployee.seniority < 2) {
    return 0;
  }
  if (anEmployee.monthsDisabled > 12) {
    return 0;
  }
  if (anEmployee.isPartTime) {
    return 0; // compute the disability amount
  }
}

There is a series of condition checks here, all pointing to the same result. Since the results are the same, these condition checks should be combined into a single expression. Condition checks executed in this sequence can be combined using logical OR operators.

public int disabilityAmount(Employee anEmployee) {
  if ((anEmployee.seniority < 2) || (anEmployee.monthsDisabled > 12)) {
    return 0;
  }
  if (anEmployee.isPartTime) {
    return 0;
  }
  return 1;
}

Then incorporate the next conditional check:

public int disabilityAmount(Employee anEmployee) {
  if ((anEmployee.seniority < 2) || (anEmployee.monthsDisabled > 12) || (anEmployee.isPartTime)) {
    return 0;
  }
  return 1;
}

After the merger is completed, use the [refining function] on this conditional expression.

public int disabilityAmount(Employee anEmployee) {
  if (isNotEligableForDisability(anEmployee)) {
    return 0;
  }
  return 1;
}

public boolean isNotEligableForDisability(Employee anEmployee) {
  return ((anEmployee.seniority < 2) || (anEmployee.monthsDisabled > 12) || (anEmployee.isPartTime));
}

Case 2: Logical AND

For example, the case of nested if statements:

public double disabilityAmount(Employee anEmployee) {
  if (anEmployee.onVacation) {
    if (anEmployee.seniority > 10) {
      return 1;
    }
  }
  return 0.5;
}

They can be combined using the logical AND operator:

public double disabilityAmount(Employee anEmployee) {
  if ((anEmployee.onVacation) && (anEmployee.seniority > 10)) {
    return 1;
  }
  return 0.5;
}

If the original conditional logic mixes both cases, I would also use a combination of logical AND and logical OR operators as needed. At this time, the code is likely to become confusing, so I will frequently use [Extract Function] to make the code readable.

おすすめ

転載: blog.csdn.net/dongnihao/article/details/131744457