Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 48 ยท Protocols, Errors and Tooling

Protocols and Behaviours

Learn Elixir polymorphism: defprotocol and defimpl for data types, behaviours with @callback and @impl for modules, and the built-in Enumerable and Inspect protocols.

Sooner or later you want one operation to work on many kinds of things: print any value, count the items in any collection, charge any payment provider. Languages with classes use inheritance for this. Elixir has no classes, and offers two separate tools instead. Protocols pick behavior based on the type of the data you pass in. Behaviours describe a contract that a module promises to fulfill, so callers can swap one module for another.

They are easy to confuse because both define "a set of functions". The difference is where the choice happens: a protocol dispatches on the first argument's type at runtime, while a behaviour is a list of callbacks that you invoke on a module you already picked. This lesson covers both, plus two protocols that ship with Elixir. It builds on maps and structs and functions and modules.

Elixir is not installed on this site, so the Elixir code is read-only. The JavaScript TryIts are stand-ins that imitate dispatch (a lookup table keyed by type, and a module-like object checked against a contract). They are not how the BEAM does it.

Protocols: dispatch on data

Define a protocol with defprotocol, listing the functions it requires. Then add implementations for each type with defimpl:

ELIXIR
defprotocol Describe do
  @doc "Returns a short human description of the value"
  def describe(value)
end

defimpl Describe, for: Integer do
  def describe(n), do: "the integer #{n}"
end

defimpl Describe, for: BitString do
  def describe(s), do: "the text #{inspect(s)}"
end

defimpl Describe, for: List do
  def describe(list), do: "a list of #{length(list)} items"
end

Describe.describe(42)         # "the integer 42"
Describe.describe("hi")       # "the text \"hi\""
Describe.describe([1, 2, 3])  # "a list of 3 items"

Calling Describe.describe/1 looks at the type of its first argument and calls the matching implementation. A value with no implementation raises Protocol.UndefinedError, which is often what you want: it tells you the type was never meant to be supported.

Note that strings are implemented for BitString, because a string is a binary, which is a kind of bitstring. The built-in type names you can use after for: are Atom, BitString, Float, Function, Integer, List, Map, PID, Port, Reference and Tuple, plus Any and the name of any struct.

Protocols and structs

Protocols shine with your own structs. Anyone can add an implementation later, even in a different library, without editing your module:

ELIXIR
defmodule User do
  defstruct [:name, :email]
end

defmodule Product do
  defstruct [:title, :price]
end

defimpl Describe, for: User do
  def describe(%User{name: name}), do: "user #{name}"
end

defimpl Describe, for: Product do
  def describe(%Product{title: title, price: price}), do: "#{title} at $#{price}"
end

Describe.describe(%User{name: "Ada", email: "[email protected]"})   # "user Ada"
Describe.describe(%Product{title: "Lamp", price: 30})             # "Lamp at $30"

This is the opposite trade-off from classes: adding a new type is easy (write a new defimpl), and adding a new operation is easy too (write a new protocol and implement it for the types you need).

Protocol or behaviour?

Protocol Chooses code by the type of the data.
Behaviour A contract that a module promises to follow.

Protocol = "what kind of value?" Behaviour = "which module plays this role?"

1 / 2

Fallbacks and deriving

If most types should share one answer, implement the protocol for: Any and opt in. There are two ways. Set @fallback_to_any true in the protocol, and every type without its own implementation uses the Any one. Or keep the protocol strict and let each struct opt in with @derive:

ELIXIR
defimpl Describe, for: Any do
  def describe(_), do: "something"
end

defmodule Point do
  @derive Describe
  defstruct [:x, :y]
end

Prefer the explicit @derive where you can, so unsupported types still fail loudly. @fallback_to_any true is convenient but silences that safety net.

Built-in protocols you already use

Several everyday features are protocols:

Protocol What it powers
Enumerable Everything in Enum and Stream: lists, maps, ranges and your own collections
Collectable The :into option of for and Enum.into/2
String.Chars to_string/1 and "#{value}" interpolation
Inspect How inspect/1, IO.inspect/1 and IEx print a value
List.Chars to_charlist/1

Implement String.Chars to make a struct work in interpolation, and Inspect to control how it prints, for example to hide a secret:

ELIXIR
defmodule Account do
  defstruct [:owner, :token]
end

defimpl String.Chars, for: Account do
  def to_string(%Account{owner: owner}), do: "account of #{owner}"
end

defimpl Inspect, for: Account do
  def inspect(%Account{owner: owner}, _opts), do: "#Account<#{owner}, token hidden>"
end

"#{%Account{owner: "Mia", token: "s3cret"}}"    # "account of Mia"
IO.inspect(%Account{owner: "Mia", token: "s3cret"})   # prints #Account<Mia, token hidden>

For Inspect there is an even simpler way to hide fields: @derive {Inspect, except: [:token]} above defstruct. Implementing Enumerable is more involved (it needs reduce/3, count/1, member?/2 and slice/1), but once a struct implements it, every Enum function works on it.

JS Protocol dispatch in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Behaviours: contracts for modules

A behaviour is a list of callbacks: function names with their types. A module that adopts it promises to define them all. Declare callbacks with @callback and adopt the behaviour with @behaviour:

ELIXIR
defmodule Notifier do
  @callback send_message(recipient :: String.t(), text :: String.t()) ::
              :ok | {:error, term()}

  @callback name() :: String.t()
end

defmodule EmailNotifier do
  @behaviour Notifier

  @impl true
  def send_message(recipient, text) do
    IO.puts("email to #{recipient}: #{text}")
    :ok
  end

  @impl true
  def name, do: "email"
end

defmodule SmsNotifier do
  @behaviour Notifier

  @impl true
  def send_message(_recipient, text) when byte_size(text) > 160, do: {:error, :too_long}
  def send_message(recipient, text) do
    IO.puts("sms to #{recipient}: #{text}")
    :ok
  end

  @impl true
  def name, do: "sms"
end

@impl true marks a function as a callback implementation. It is optional, but the compiler then warns you about missing callbacks, about functions that do not match any callback, and it improves documentation. Once you use @impl on one function in a module, use it on all callbacks of that behaviour.

A caller works against the contract and receives the actual module as data:

ELIXIR
def alert(notifier, user, text) do
  notifier.send_message(user, text)
end

alert(EmailNotifier, "[email protected]", "Build finished")

That notifier.send_message(...) call, with a module held in a variable, is the heart of the pattern. In tests you pass a fake module that follows the same behaviour (testing with ExUnit will use this). Optional callbacks are declared with @optional_callbacks [name: 0]. Behaviours such as GenServer, Supervisor and Application are how the OTP libraries ask your code to plug in.

JS A behaviour as a checked contract, in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choosing between them

Question Protocol Behaviour
What decides which code runs? The type of the first argument The module you pass or configure
Typical use Printing, converting, iterating data Swappable services, plug-in points
Defined with defprotocol / defimpl @callback / @behaviour
Dispatch cost A lookup, cached after compilation (consolidated protocols) A normal module call

If your function must behave differently for different kinds of values, use a protocol, or even simpler, multiple clauses with patterns. If your function must be replaceable by a different implementation of a service, use a behaviour. Do not create a protocol when a pattern match on a few known shapes does the job.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a protocol dispatch on?

    A protocol call looks at the data type of the first argument and runs the matching defimpl.
  2. 2. What happens if you call a protocol function with a type that has no implementation and there is no Any fallback?

    Protocol.UndefinedError makes unsupported types fail loudly instead of guessing.
  3. 3. What does @impl true on a function do?

    @impl documents the intent and lets the compiler warn about missing or unmatched callbacks.
  4. 4. Which protocol controls how a struct appears in IEx and with IO.inspect?

    Inspect is used for debugging output. String.Chars is for to_string and interpolation.

Summary

  • A protocol (defprotocol + defimpl) chooses behavior by the type of the first argument, and you can add implementations for types you do not own.
  • Unsupported types raise Protocol.UndefinedError; for: Any with @derive or @fallback_to_any offers defaults.
  • Enumerable, Collectable, String.Chars, Inspect and List.Chars are built-in protocols behind Enum, for, interpolation and printing.
  • A behaviour (@callback + @behaviour) is a contract for modules; mark implementations with @impl true.
  • Pass modules around as values to swap implementations, including fakes in tests.
  • Prefer plain pattern matching until you truly need extensibility.

Next, see how Elixir code can write code: Metaprogramming and Macros.