r/ProgrammerAnimemes • • May 20 '23

Ternary operator

Post image
1.5k Upvotes

41 comments sorted by

View all comments

Show parent comment

4

u/[deleted] May 21 '23

Question, why in fuck's name would you use a ternary for this and not a switch case or even just nested if/else statements? It seems unnecessarily difficult to read in comparison. I always thought ternaries were only really useful to replace an if statement and keep things inline.

4

u/bucket3432 May 22 '23

The specific example in the meme is obviously pretty contrived, so take it with a grain of salt. But you may want to consider nested ternaries for when you have maybe 3 or fewer outcomes (one level of nesting), and especially when you have closely related outcomes but dissimilar conditions.

When a codebase tends towards a more functional style, which can be common for function bodies, it can be more natural to reach for expressions such as the ternary operator for their ability to compose with other expressions. In an equally contrived example extending the ternary in the meme, consider this JavaScript chain:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  .filter((n) => n < 5)
  .map((n) => (
      n == 1 ? "one"
    : n == 2 ? "two"
    : n == 3 ? "three"
             : "other"
  )).join(", ");

The ternary fits very compactly in the map body and it's clear from the context what it's meant to do (assuming you know what map does). Using an if or switch statement, you'd probably end up using at least double the number of lines, and increasing verbosity can sometimes lead to code being less readable. In this case, it's not too bad if your style guide allows for the case keyword and the body to be on the same line, but the verbosity of the switch statement adds extra clutter in my opinion:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  .filter((n) => n < 5)
  .map((n) => {
    switch (n) {
      case 1: return "one";
      case 2: return "two";
      case 3: return "three";
      default: return "other";
    }
  }).join(", ");

As /u/ThePyroEagle mentioned, pattern matching might work better in this situation. JavaScript doesn't have pattern matching, but you can get close with an object map:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  .filter((n) => n < 5)
  .map((n) => (
    {
      [1]: "one",
      [2]: "two",
      [3]: "three",
    }[n] ?? "other"
  )).join(", ");

I've personally used this pattern in production code as it's one of the ways to reduce cyclomatic complexity (Wikipedia), but it might be too clever for some people. This pattern shares the advantage as the ternary in that it's also an expression and can be composed with other expressions.

In a less contrived example, suppose you need a variable to determine a user's permission level (UNAUTHENTICATED_USER, REGULAR_USER, ADMIN_USER) based on whether they're authenticated (isAuthenticated, boolean) and whether they're an admin (isAdmin, boolean). A switch statement won't help you here because you need to take into account two inputs (we're not considering switch (true) hacks here). You could write it with nested ternaries:

const userLevel = !isAuthenticated ? UNAUTHENTICATED_USER
                : isAdmin ? ADMIN_USER
                : REGULAR_USER;

Or you could write it with an if-else statement:

let userLevel;
if (!isAuthenticated) {
  userLevel = UNAUTHENTICATED_USER;
} else if (isAdmin) {
  userLevel = ADMIN_USER;
} else {
  userLevel = REGULAR_USER;
}

The ternary is more compact and less verbose than the if-else statements and that makes it much easier to read at a glance in my opinion. You could be more compact by removing the braces in the if statement, but I suspect not many style guides will allow that:

let userLevel;
if (!isAuthenticated) userLevel = UNAUTHENTICATED_USER;
else if (isAdmin)     userLevel = ADMIN_USER;
else                  userLevel = REGULAR_USER;

But perhaps more importantly, the ternary allows us to keep the variable const, which prevents the variable from being reassigned later in the code. Using const wherever possible is best practice in JavaScript, and more generally using immutable variables is best practice in functional-style programming. That is something that's not possible to do directly with the if statement since using a single variable requires conditional assignment of that variable, and if statements cannot be used directly in assignments as the right-hand side of an assignment requires an expression.

To be able to use const with an if statement, you could use an immediately invoked function expression (IIFE)):

const userLevel = (() => {
  if (!isAuthenticated) {
    return UNAUTHENTICATED_USER;
  } else if (isAdmin) {
    return ADMIN_USER;
  } else {
    return REGULAR_USER;
  }
})();

Or pull that logic out into a separate function altogether:

const userLevel = calculateUserLevel(isAuthenticated, isAdmin);

The IIFE feels forced to me, and not all languages support IIFEs anyway. Refactoring to a separate function is absolutely valid, but sometimes it's overkill for a single-use piece of logic and you're just pushing the problem of readability to the function body.

Readability is ultimately subject to the reader's background and familiarity with the construct. Someone who is accustomed to more procedural settings will likely encounter fewer ternaries and will find it less readable than someone who is more familiar with functional code and sees them more often.

2

u/ThePyroEagle λ May 21 '23

In this toy example, a switch or pattern match works better, but sometimes conditionals can't be (concisely) expressed that way.