John Chamberlain
Developer Diary
 Developer Diary · You Heard It Here First · Saturday 6 March 2004
Principles of Programming: Test for the Positive Case
Another great but simple principle of programming is to test for the positive case. This may sound pretty obvious but in practice most programmers are just as likely to test for the negative as test for the positive. I even see double negatives like if( my_variable != false )... and similar constructions. Another classic along the same lines is while( c = getchar() != EOF ).... While this has some logic to it the reality is that if you test for either true or false equally often boolean confusion sets in eventually. The secret is to bias your code in favor of testing for the positive case. This makes it easier to understand and more parallel (another principle). Often I will have nothing but a comment in my positive case just to maintain this parallelism, for example:
    if( zDidItWork() ){
        // ok
    } else {
        sbError.append("it didn't work");
        return false;
It is a slightly more wordy way of doing things but keeping all my if statements positive reduces bugs and increases readability in the long term.
return to John Chamberlain's home · diary index
Developer Diary · about · · bio · Revised 6 March 2004 · Pure Content