This style gets the label 'poor-mans-pattern-matching' from me. If pattern matching would not be in my daily vocabulary, as it's also not available in JS, I'd consider it a misuse of switch/case and this post also makes an odd example for its usefulness.<p>The example I would pick is the following: Consider you need to switch depending on a version (of a specification in my case), but this version isn't represented as an enum in the codebase, but as a number instead. So our team had something like this in the codebase (early return):<p><pre><code> function foobar(version: number): string {
if (version === 3.1 || version === 3) {
return 'result_3';
}
if (version < 2 && version >= 1) {
return 'result_1';
}
if (version >= 2) {
return 'result_2';
}
throw new Error(`Cannot interpret version '${version}'`);
}
</code></pre>
I read it as "people don't care about branching order that much, so how can I make my wish for better readability more clear?".... my end goal then was to bring it into this state (a distinct enum as discrete value of the version):<p><pre><code> enum Version {
_1_1 = 1.1,
_2 = 2,
_3 = 3,
_3_1 = 3.1,
};
function foobar(version: Version): string {
switch (version) {
case Version._3_1:
case Version._3:
return 'result_3';
case Version._2:
return 'result_2';
case Version._1_1:
return 'result_1';
default:
(function (val: never): never {
throw new Error(`Exhaustiveness reached: ${val}`);
})(version);
}
}
</code></pre>
...and my interim solution that made it into the PR in time turned out to be something like this (switch true):<p><pre><code> function foobar(version: number): string {
switch (true) {
case version >= 3:
return 'result_3';
case version >= 2:
return 'result_2';
case version >= 1:
return 'result_1';
default:
throw new Error(`Cannot interpret version '${version}'`);
}
}
</code></pre>
My PR was flagged by the team for misuse of the switch statement, we had some discussion and I changed it back to the simple if/else branching from above.