Behaviors in Elixir are the interfaces that are in Object-Oriented Programming. They provide an abstract definition of a module for testing. A behavior typically consists of a set of functions that need to be implemented by the module.
Behaviours ensure that:
In case the function inside a behavior is not implemented, :error
is raised.
For instance, we can ensure that certain modules parse strings. For this, we can introduce a Parse
behavior, such as the example below:
defmodule @Parse do @doc ''' Parse a string ''' @callback parse(String.t) :: {:ok, term} | {:error, String.t} end
Now this behavior is implemented in a module:
defmodule JSONParser do @behaviour Parse @impl Parse def parse(str), do: {:ok, "some json " <> str} # ... parse JSON end
Asserting that the module JSONParser
has behavior Parse
, we can ensure that the function parse()
returns a string. The absence of the function or the wrong return type would have raised an error.
RELATED TAGS
CONTRIBUTOR
View all Courses