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"
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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"
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 propertyisInactive
. 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