Prefer positive conditionals/checks
In conditionals - like if
, ternary, boolean variables, prefer storing/checking positive conditions over equivalent negative ones.
what is positive depends on the goal of the feature.
// example 1
const hasNoEnergy = !getStatus(); // problem: negative stored in boolean
if (hasNoEnergy) {
injectFuel();
} else {
changeOrbit();
}
// example 2
const hasEnergy = getStatus();
if (!hasEnergy) { // problem: negative checked in if
injectFuel();
} else {
changeOrbit();
}
// these are complicated, need to be read deliberately
// simple, better
const hasEnergy = getStatus();
if (hasEnergy) {
changeOrbit();
} else {
injectFuel();
}
Top comments (0)