liveBook · Manning

Callback module

As explained in Elixir in Action, Third Edition

A callback module is a module that exports functions invoked by a generic component to provide application-specific behavior.

A callback module supplies application-specific decisions to generic code. The generic component accepts the module, keeps its module name as process state, and invokes exported callback functions when it needs behavior it cannot determine itself. section 6.1.1 section 6.2.1

The pattern separates process mechanics from domain logic. Generic code handles spawning, looping, message passing, replies, and state replacement; the callback module initializes state and handles requests. section 6.1.2 section 6.1.3

Key-value store callback

A KeyValueStore callback module can define init/0 to return an empty map and handle_call/2 clauses for putting and getting values. Starting ServerProcess with KeyValueStore plugs this implementation into the generic server; interface functions can hide that arrangement from clients. section 6.1.3 section 6.1.2

In OTP, a behaviour formalizes the contract. GenServer callback modules commonly implement init/1, handle_call/3, handle_cast/2, and handle_info/2, while GenServer supplies the generic server process. section 6.2.1 section 6.3

The same pattern configures supervisors and applications. A supervisor callback module implements init/1 to return child specifications and options; an application callback implements start/2, usually starting the top-level supervisor. section 8.3.5 section 11.1.2

iex(1)> some_module = IO           #1
 
iex(2)> some_module.puts("Hello")  #2
Hello

Use a module atom as a value, then invoke an exported function through that value—the runtime mechanism behind generic callback dispatch. section 6.1.1

How Elixir in Action, Third Edition covers it

How deep it goes
Explains dynamic dispatch, callback contracts, state transitions, and OTP applications, while deferring detailed behaviour documentation.
Examples
Uses a key-value store, generic ServerProcess, supervisor initialization, and automatic OTP application startup.
What it assumes
Assumes Elixir modules, functions, processes, and message passing while introducing behaviour contracts through runnable server examples.
What you can do after
Builds callback modules for generic servers, supervisors, and applications, then exposes simpler client-facing interface functions.
How it connects
Connects callback modules with behaviours, GenServer, Supervisor, Application, supervision trees, and message passing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.