Re:Using the switch(true) pattern in JavaScript
by brundolf on Monday April 12, 2021 @03:50PM
(#26784264)
You're right that both technically qualify as early-return, which is why I qualified my original statement with "if you don't put the rest of the function in an else clause".
In practice, in C-like languages, I tend to see the "else-less" version which is why I brought it up
Re:Using the switch(true) pattern in JavaScript
by kbenson on Monday April 12, 2021 @08:19PM
(#26786747)
If you haven't seen it, Kevlin Henney's talk about "The Forgotten Art of Structured Programming"[1] is interesting (if somewhat long in the examples later), and somewhat related. It's not specifically about return early (and a case could be made that it should or should not apply specifically to early return), but it is about if, else, return, and how they affect cognitive load when reading code.
That is, I don't think it matters too much whether you do:
or as they both accomplish the same major benefit of the pattern.The real thing it's helping to avoid is accidentally creating something like this:
which can quickly get very hard to reason about without in more complex cases.