TIL: Cognitive Complexity

I saw some nested if statements somewhere in the codebase, and sonarlint said Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed. [+8 locations]sonarlint(typescript:S3776)

Naturally, looked into it a bit more, and here’s some stuff I found, figure it may be of interest to others.

It’s nice to have the word for this, because every time I see deeply nested flow control statements, my gut feel is usually “this is hard to read/understand” - usually because it’s challenging to visualise all the possible states that the piece of code could be in.

From Armand

Instead of doing

let descriptiveReason = ""
switch(reason) {
  case "something":
    descriptiveReason = "It was something"
  case "something_else":
    descriptiveReason = "It was something else"
    descriptiveReason = "It was nothing"


const descriptors = {
  "something": "It was something",
  "something_else": "It was something else",
  "nothing": "It was nothing"

let descriptiveReason = descriptors[reason || "nothing"]