How To Overload Function In Elixir — Tentamen Software Testing Blog

Image by from

TL;DR

In the previous post, we gave an introduction to . Today we explain how to overload function in Elixir. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

What Is Overload

Function overload is the case when we have several definitions of the same function name and arity. Elixir pattern matches input parameters and decides which definition to call. As in regular pattern matching, the order of matching is top/down direction. We overload the function that calculates VAT tax for a beer price:

We first calculate beer price in Croatia, and after that, we put the wrong input to trigger FunctionClauseError.

Run for overloaded price function

FunctionClauseError usually indicates a bug in a program.

Whole Function

It is important to understand that we do not have three price functions, just one:

The overloaded function is the whole function.

Error Instead Of FunctionClauseError

It is good practice to explain to users what went wrong with provided input. So last overloaded function should return an error that provided input could not be processed:

Note that we add to map additional key, function overloading still works because we still hit arity/1. But with arity/2, we got FunctionClauseError

Function overload with default clause.

Remember

  • return an error instead of FunctionClauseError
  • order of function overloading is top/down
  • overloading works only for the same function arity

Originally published at on February 16, 2021.

--

--

--

Founder of Tentamen, software testing agency.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Migrating Superset to Postgres

Continuous Backups with Point-in-Time restores in Azure Cosmos DB

How to Build a Search Engine in Under 20 lines of Code — in R

Difference between HTTP1.1 vs HTTP2

Yep, SaaS software is hard to get right, even as it gets better, faster and even easier to adopt.

Testing From Trenches, How To Find Errors In Book Manuscript — Tentamen Software Testing Blog

Unit Testing Techniques and Best Practices

How to connect to Mysql using C++ in Mac OSX

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
Karlo Smid

Karlo Smid

Founder of Tentamen, software testing agency.

More from Medium

Elixir’s best practices: Achieve secure authentication

Ranked data with Ecto window Queries

Comparing dates in Elixir