Do you use logical negation operator (!) in "if" statement or check on "== false"

Posted by Taras Terebkov on Stack Overflow See other posts from Stack Overflow or by Taras Terebkov
Published on 2010-03-17T08:53:41Z Indexed on 2010/03/17 9:01 UTC
Read the original article Hit count: 182

Filed under:
|
|
|

Hello everyone,

I just want to conduct a little survey about code style developers prefer.

For me there are two ways to write "if" in such languages as Java, C#, C++, etc.

(1) Logical negation operator

public void foo() {
   if (!SessionManager.getInstance().hasActiveSession()) {
       . . . . .
   }
}

(2) Check on "false"

public void foo() {
    if (SessionManager.getInstance().hasActiveSession() == false) {
        . . . . .
    }
}

I always believe that first way is much worst then the second one. Cause usually you don't "read" the code, but "recognize" it in one brief look.

And exclamation symbol slipped from your mind, just disturbing you somewhere on the bottom of your unconscious. And only during reading the "if" block below you understand, that the logic is opposite - no sessions in "if"

On the other hand in the second way of writing, an eye immediately catches words "SessionManager", "hasActiveSession" and "false".

Also for me, the situation with "true" is different. In code like

class SessionManager {
    private bool hasSession;

    public void foo() {
        if (hasSession == true) {
            . . . . .
        } else {
            . . . . .
        }
    }
}

I find "true" superfluous. why we repeating the sentence two times? The following is shorter and quicker to catch.

class SessionManager {
    private bool hasSession;

    public void foo() {
        if (hasSession) {
            . . . . .
        } else {
            . . . . .
        }
    } 
}

What do YOU think, guys?

© Stack Overflow or respective owner

Related posts about code-style

Related posts about c++