A couple of weeks ago, my friends raised a question as this. Is is harmful to have a use of If without Else? As soon as I saw the question, I answered Yes, because I am a functional programmer. Generally, there is no use of IF without ELSE in functional programming languages.
I'd like to argue why IF had better be paired with ELSE. Let us consider a little code as:
(1) if ( cond ) x = e1; else x = e2; // in the C programming language
// e1 and e2 are assumed to be free from side-effects.
One could rewrite (1) as follows:
(2) x = e2; if ( cond ) x = e1;
Actually, (1) and (2) are equivalent to each other; In (2), the IF can be regarded as one with ELSE. Therefore, this pattern of the use of IF is satisfactory.
The last code pose some problem that I will explain.
(3) if ( cond ) x = e1;
If the cond evaluates to false, it is unknown
- whether x is initialized properly, and
- what value x is initialized with
To know what are unknown stated above, one must examine the context where the code (3) is used. Otherwise, you can't understand what will happen on the negative condition.
One can understand the meaning of (1) locally, just by looking at the code itself, while he or she cannot understand (2) locally because the meaning of (2) depends on the context surrounding it. The local understanding is better than the non-local understanding. This is the reason why IF-ELSE is preferable to IF unpaired with ELSE.
If you are still not so convinced of the advantages of the use of the IF-ELSE pair, you may choose the following option:
(4) if ( cond ) x = e; /* no else */
The comment following the IF explicitly states that the programmer knows that he or she omits ELSE intentionally, not accidentally.
I am curious about other's opinions. Please leave your comments.