Expanding Control Guard Clauses
Learn about how guard clauses help expand control to improve code.
Introduction to guard clauses
Creating multiple functions with pattern matching to control the program flow can be exhausting sometimes. In the example where we made the NumberCompare
module, we have to build auxiliary functions to handle the >=
operation result. Creating too many functions for trivial tasks can generate code that is hard to maintain. We can improve this using Elixir guard clauses. Guard clauses permit us to add Boolean expressions in our functions, adding more power to our function clauses.
Creating the guard clause
We can create guard clauses by using the when
keyword after functions’ parameters. Let’s see how it works for improving our NumberCompare
code:
defmodule NumberCompare do def greater(number, other_number) when number >= other_number, do: number def greater(_, other_number), do: other_number end
Running the above will launch a terminal. Try the code below in it:
$ iex
iex> c("number_compare.ex")
iex> NumberCompare.greater(2, 8)
#Output -> 8
We’ve used the guard clauses to check which number is greater; one function returns the first number, and the other returns the second. The expression when number >= other_number
is the guard clause. The function will be executed when it’s true
, returning the variable number
. When the expression is false
, it will try to run the second function clause. The second clause will always match because it doesn’t have any checks to prevent execution.
Guard clauses help us create better function signatures and, reduce the need for function helpers. We can also use guard clauses to enforce which data we’re expecting. Let’s improve the Checkout
module that we created in the previous ...