3 ms·
If you have a chain of conditions what you do? if (condition1) { // something } if (!condition1 && condition2) { // other stuff
by alerighi 6y ago
If you have a chain of conditions what you do?
if (condition1) {
// something
}
if (!condition1 && condition2) {
// other stuff
}
if (!condition1 || !condition2) {
// finally
}
An if-else is more clear:
if (condition1) {
// something
} else if (condition2) {
// other stuff
} else {
// finally
}
To me if-else is more easy to reason about (since it's clear that you enter in one of the 3 possible branches without even looking at the conditions), but also it's more efficient, especially if the condition is not a trivial comparison (for example you are comparing strings, or doing some other linear operation. And yes, computer are fast these days, but there are no excuse for wasting resources for nothing to me).
- TeMPOraL 6y agoIf that if/else chain is returning a value, then what's even more clear is: if (condition1) { return something; } if (condition2) { return otherStuff; } return finally; I don't remember the last time I wrote an if/else chain that wasn't in return position.