Multiple Conditional Check in Programming – Readability Case Study

data codes through eyeglasses

One of the problems we encounter when trying to write clean code is having to check multiple conditions at once as in the case we describe in this article. While there is no correct answer I could able to give, I want to point out the importance of the decision between the approaches I have presented here.

As the smallest readability decrease may result in the increased cost of maintenance in huge codebases, it is wise to think about each of the little cases carefully.

The scenario arises when multiple conditions have to be mapped to the same output. Here approach 1 presents the simple implementation of the case while approach 2 and approach 3 form alternative implementation.

Approach 1

Here, the simple implementation of the validation function is shown. The function has to pass if and only if all of the preconditions are met.

STATE validate() {
  STATE result = SUCCESS;

  if (mid_length_condition()) {
    result = FAIL;
  } else if (mid_length_condition2()) {
    result = FAIL;
  } else if (mid_length_condition3()) {
    result = FAIL;
  } else if (mid_length_condition4()) {
    result = FAIL;
  } else if (mid_length_condition5()) {
    result = FAIL;
  }

  return result;
}

Approach 2

The alternative implementation of the same function can be as follows.

This one a bit feels like the depth-first approach.

STATE validate() {
  STATE result = FAIL;

  if (mid_length_condition()) {
    if (mid_length_condition2()) {
      if (mid_length_condition3()) {
        if (mid_length_condition4()) {
          if (mid_length_condition4()) {
            result = SUCCESS;
          }
        }
      }
    }
  }

  return result;
}

Approach 3

The other alternative implementation which is much more succinct is as follows.

This one is the most succinct one. Less number of lines, but feels a bit complex.

STATE validate() {
  STATE result = SUCCESS;

  if (mid_length_condition() ||
    mid_length_condition2() ||
    mid_length_condition3() ||
    mid_length_condition4() ||
    mid_length_condition5()
  ) {
    result = FAIL;
  }

  return result;
}

Review

At this point, I expect you to give the answer as a comment and explain your decision in detail. As there are no right and wrong answers to this readability question, feel free to share any detail you like.

References

[1] Jimmy, “C Formatter,” Codebeautify.org, 2022. https://codebeautify.org/c-formatter-beautifier (accessed Jun. 15, 2022).


Leave a Reply

Your email address will not be published. Required fields are marked *