Ensuring module implements behaviour

aochagavia
Mon, 22 Aug 2022 14:18:07 +0000
Questions / Help

Context

A feature of Elixir I find myself using often when defining functions is to pattern match on structs. This way I can ensure the function is being called with the data I expect, get nice autocompletion in my IDE and even get compile errors if I ever modify the names of the fields of the struct and forget to update them at the function definition.

Consider the (utterly simplified) example below:

def get_name(%Employee{name: name}) do
  name
end

Question

Sometimes a function takes a module instead of a struct. In those cases, it would be very useful to have a lightweight way of enforcing that the module implements a particular behaviour (either through pattern matching or through guards would be ideal).

An example with hypothetical syntax:

def sort(list, sorting_module) when implements_behaviour(sorting_module, SortingAlgorithm) do
  sorting_module.sort(list)
end

I can imagine there are more people like me who like to enforce invariants in their code. Hence my question: are there any Elixir idioms to ensure a module implements a behaviour? Or is this somehow not “the Elixir way”?

11 posts - 6 participants