DEV Community

loading...

Discussion on: Write better code and be a better programmer by NEVER USING ELSE statements

Collapse
dglsparsons profile image
Douglas Parsons Author

How do you mean 'negative logic' ?

Collapse
hasii2011 profile image
Humberto A Sanchez II

The code showed this:

function doSomething() {
if (something.OK()) {
return something.Do()
}
}

It was changed to:

function doSomething() {
if (!something.OK()) {
// return or throw error
}
return something.Do()
}

My experience has been that using a "not" in front of a conditional requires a mental adjustment to process the "negative" condition. I think I also read this on many books that talk about "code smells"

Thread Thread
dglsparsons profile image
Douglas Parsons Author

I think it depends on the properties/methods you have. I agree with your point that putting 'not' in front of a conditional can require a mental adjustment, but that's usually when you're properties are negative or poorly named.

For example - if I had a something.notOK() method, I wouldn't want to negate this - as !something.notOK() doesn't read very nicely.

That's an extreme example, but it's why naming is super important (especially for booleans).

Another example could be flagging users as inactive - the logical thing to do is to add a boolean property isInactive. This isn't as obviously terrible, but inverting this can be confusing - not isInactive... so active.

I'd argue the code smell there is the names / properties, rather than inverting the if / else statements though.

Great point though <3

Collapse
sctgcs profile image
Simon Tillson

He means inverted logic, not negative logic. In boolean terms, they're equivalent.