Guard Clauses
Methods can become difficult to read when nested conditionals are introduced. Even in simple examples like the one below, determining under what conditions the method gets executed is slightly ambiguous. The sideways pyramid shape that the code is taking on is adding unnecessary burden to your eyes as you scan the screen.
Guard clauses can fix this problem by eliminating nested conditionals. A guard clause simply return
s from the method when a given condition is met:
This is a much cleaner way to validate inputs to a method. It is much easier to read and determine under what conditions that the method would be run.