[English] Tip for quick bug finding: Follow the line of sight

Guilherme Tavares's code bug photo, licensed as CC BY 2.0

What can we do to find bugs quickly?

To fix bugs we need to quickly undestand the logic flow of the code. Having deeply nested if-else statements hurt code glanceability. We could improve code glanceability.

What I mean with glanceability? Let’s see an example.

Can you see where is the “happy path” and where are the “error paths” only by glancing at this blocks of characters without knowing the real code?

process <- function(authorization_header, bearer_token) {
  status <- ""

  if (authorization_header != "") {
    if (length(bearer_token) != 2) {
      status <- "ok"
    } else {
      status <- "invalid bearer token format"
    }
  } else {
    status <- "missing authorization header"
  }

  return(status)
}


Having nested happy paths increases the cognitive load. We have to actually read the code in order to understand the happy and error paths.

Moving nested ifs to “Guard statements” without "else" statements translates to less cognitive effort undestanding the code, because having left-aligned happy path make each code “happy path” and “error paths” obvious.

Ok. Try again.

Can you see where is the “happy path” and where are the “error paths” only by glancing at this blocks of characters without knowing the real code?

process <- function(authorization_header, bearer_token) {
  if (is.null(authorization_header) || authorization_header == "") {
    return("missing authorization header")
  }

  if (length(bearer_token) != 2) {
    return("invalid bearer token format")
  }

  "ok"
}


The vertical line at the minimum indentation level represents the "core logic".
Any vertical line with more indentation represents anything out of the ordinary: error handling and guards.

And since our eyes are very good at following lines, the line of sight (the vertical line at the minimum indentation level) guides us and greatly improves the experience of glancing at a piece of code.

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *

This site uses Akismet to reduce spam. Learn how your comment data is processed.