DEV Community

Discussion on: The Power of Guard Clauses

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

A very simple function. One recommendation you might have stumbled over already is to avoid else as much as possible. In this case, it's a very valid choice to make the code just a hint more readable.

Couldn't disagree more. Keep your code 2D: use indentation (along with newlines) to communicate parallelism in code paths. The second example is, in my view, greatly inferior in terms of readability than the first one.

Reject early with guard clauses

With that, the main point of the article, I 100% agree though. Structuring a subroutine as

  1. Reject invalid input data
  2. Process input data
  3. Return results

makes it easier to follow the logic. We're used to having information about the input parameters at the beginning of the function (usually in the function declaration), and putting additional constraints right after that makes sense.