IF ELSE Statement

The orthodox IF ELSE Statement is IF Condition_1 THEN Function_1 ELSE Function_2. Indeed, this is a simplified statement of: IF Condition_1 THEN Function_1 ELSE IF Condition_2 THEN Function_2. By saying that, the perfect relationship between Condition_1 (C1) and Condition_2 (C2) consists of:

1. The union of Condition_1 and Condition_2 (C1 ∪ C2) covers every possible situations, while
2. they do not have intersection (A ∩ B = 0).

For instances:

Example 1: if(0<C) {F1} else {F2}
Example 2: if(0<C) {F1} else if(0>C) {F2}
Example 3: if(0<=C) {F1} else if(0=>C) {F2}

Example 1 is perfect okay because the implicit Condition_2 covers everything else other than Condition_1. Example 2, however is not such perfect because it does not cover every situations, thus leave a possible logic bug. Example 3 contains logic error because there is intersection between two conditions. It is therefore suggested when use IF ELSE Statement, it shall cover all situations but not overlapped unless you are fully aware what was left behind.

However, when two sets of conditions apply, it because much complicated. For instance:

if(0<C) {F1}
else if(0==C || 100==C2) {F2}
else if(0>C) {F3}
else {F4};

You would never get clear logic set here. Actually, you can, after conditions cover full combinations/metrics of two sets. What about three sets conditions? You should try to avoid this kind of situation. However, if you can't, there is a suggestion:

1. Employ a middle layer, say Action, between Conditions and Functions. Unlike Functions, Actions are just flags of Functions and some of them can override others.
2. Use several IF Statements instead of a single IF ELSE Statement to cover every situations selected by you.
3. Because some Actions may override others, so, careful arranging the orders of IF Statements is necessary.

Here is the example:

if(0==C || 100==C2) {A1};
if(0<C) {A2};
if(0>C || 1!=C3) {A3};
if(0>C) {A4};
if (A1) {F3}
else if (A2) {F1}
else if (A3) {F4}
else {F3};

Done. Just be very careful all necessary situations need to be covered and action overriding order need to be correctly arranged. Else, you just prepare to deal with the logic bugs.

No comments:

Post a Comment

Labels