Elixir Short Circuit Operators — Tentamen Software Testing Blog

Image for post
Image for post

TL;DR

In the previous post, we explained Elixir Atoms. Today we discuss Elixir short circuit operators and how those could help you to write less code. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Short Circuit Operators

Short Circuit Operators in Elixir are boolean operators. They operate on boolean values, and the result is also boolean value.

We have two Short Circuit Operators, || and &&. We use them to chain several functions that return a boolean value.

False and True

In Elixir, only nil and false are false, while all other values are true. In the image above, you can see that in practice.

||

or short circuit operator returns the first expression from the left that is not false

Image for post
Image for post

You would use || short circuit operator in your application for function chaining:

email_login || facebook_login || google_login

In this example, your application provides three ways to log in, using registered email/password credentials, Facebook, or Google login. Let users in for any of those authentication providers.

&&

and short circuit operator returns the last expression only if all expressions from left to right are true

Image for post
Image for post

You would use and short circuit operator if the user has to satisfy several conditions to log in:

same_ip && authenticated? && is_admin?

Remember

  • || returns the first expression from the left that is not false

Originally published at https://blog.tentamen.eu on July 21, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store