What is a contract?

I was exploring the source code of mix and I came upon this term called “Contract”

defmodule Mix.Shell do
  @moduledoc """
  Defines `Mix.Shell` contract.
  """

Where can I read about this contract pattern?

2 Likes

from Kernel — Elixir v1.16.0

Protocols

Protocols add polymorphic dispatch to Elixir. They are contracts implementable by data types. See Protocol for more information on protocols. Elixir provides the following protocols in the standard library:

  • Collectable - collects data into a data type
  • Enumerable - handles collections in Elixir. The Enum module provides eager functions for working with collections, the Stream module provides lazy functions
  • Inspect - converts data types into their programming language representation
  • List.Chars - converts data types to their outside world representation as charlists (non-programming based)
  • String.Chars - converts data types to their outside world representation as strings (non-programming based)

The contract are the Callbacks that you need to implement in order to implement the Mix.Shell behaviour.
The specs aid you in what to accept as arguments and what to return.

While Mix.Shell is a behaviour, not a protocol, the idea of contract applies to both Protocols and Behaviours.

You can read more about Behaviours here:
https://hexdocs.pm/elixir/Module.html#module-behaviour

3 Likes

Seems like this documentation could be improved. Let’s look at the example of GenServer:

GenServer behaviour

A behaviour module for implementing the server of a client-server relation.

A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on. The advantage of using a generic server process (GenServer) implemented using this module is that it will have a standard set of interface functions and include functionality for tracing and error reporting. It will also fit into a supervision tree.

I think Mix.Shell could be reworded to something like “A behaviour module for implementing [thing].” Not sure what “[thing]” actually is thought.

I think this is worthy of a PR.

3 Likes