💧 Elixir Intermediate

What are Elixir behaviours?

Answer

Behaviours define a set of functions (callbacks) that a module must implement — they are Elixir's way to specify a contract or interface. Define a behaviour: defmodule Parser do; @callback parse(String.t()) :: {:ok, any()} | {:error, String.t()}; end. Implement it: defmodule JsonParser do; @behaviour Parser; def parse(s) do ... end; end. The compiler warns if a required callback is missing. Common OTP behaviours: GenServer, Supervisor, Application, GenEvent. Difference from protocols: behaviours define what a module must do (module-level contract); protocols enable dispatch based on data type (value-level polymorphism). Use behaviours for: pluggable implementations (payment gateways, notification providers), testing (swap real implementation with a mock module), and defining expected interfaces for adapter patterns. Behaviours are documented via @callback annotations and type specs.