4 ms·
In short: avoid `else`. Both what you mention, and also the case with : if (...) { ... } else { return 0; } Which can become if (...
by quickthrower2 3y ago
In short: avoid `else`.
Both what you mention, and also the case with :
if (...) {
...
} else {
return 0;
}
Which can become
if (...) {
...
}
return 0;
- hedora 3y agoEven better, if you're using a language with pattern matching (rust, any ML, haskell), just put it in a single match with the happy case on top, and the error cases below. To do this, you need to encode the distinction between happy and sad path in your types. That's good for all sorts of other reasons, so it's not really a drawback.
- KineticLensman 3y agoYes, pattern matching really helps with clarity, especially when there are multiple happy paths, like in a parser
- theteapot 3y agoWhat about `else if`? Not a fan?
- quickthrower2 3y agoOccasional vice for me.
- stouset 3y agoPersonally I only either use if statements that wrap a single line of logic, or a switch/case statement where each branch is a single line of logic. Most situations are handled by guard clauses, exhaustive type switching, or switching on logical cases. Very occasionally do I have to break this practice for a legitimate reason, but this keeps functions simple to read and to reason about. I occasionally am unable to avoid an else, but I will always avoid else if. It puts too much reliance on remembering how this condition interacts with the one on the if statement above it, which can often be many lines away. I’d infinitely rather use a case statement where all the alternatives are in an easily-understood table with every condition aligned on successive lines.
- Xeamek 3y agoIn functional languages like elixir there is no return though, and you are forced to use if-else structure
- jstanley 3y agoI tend to prefer a style more like: if (!...) return 0; ... Because otherwise you can end up with lots of nested conditions which are very confusing to follow, even though they boil down to "do the thing if these are true, otherwise don't do the thing".