Comment

Comment by aastronaut

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.

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):

  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}'`);
  }
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):

  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);
    }
  }
...and my interim solution that made it into the PR in time turned out to be something like this (switch true):

  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}'`);
    }
  }
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.
parent aastronaut 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton