liveBook · Manning

Module

As explained in Elixir in Action, Third Edition

A module is a named unit of Elixir code that groups functions and other definitions for compilation and loading.

A module is a named unit of Elixir code that groups functions and other definitions. Every function belongs to a module, which acts somewhat like a namespace. section 2.3.1 section 2.3.2

Defining and calling a module

Define modules with defmodule and functions with def. Compile the source, load the resulting module into iex, and call public functions with ModuleName.function_name(arguments). section 2.3.1

Use module names and boundaries to organize code and control calling syntax:

  • Write module names with an uppercase initial; dots can suggest hierarchy and reduce naming clashes, but compiled modules have no recorded hierarchical relationship. section 2.3.1
  • Place a module definition in one source file, while allowing multiple module definitions in a single file; compilation produces a separate .beam file for each module. section 2.3.1 section 2.7.1
  • Import frequently used modules to call public functions without qualification, or alias long names to reduce repeated module-name noise. section 2.3.5
  • Treat module names as aliases for atoms at runtime; BEAM checks loaded modules first, then searches code paths for compiled bytecode. section 2.7.1

Modules provide the unit from which larger OTP applications are assembled. An OTP application contains multiple modules, may depend on other applications, and can start as one system. section 11.1 section 11.1.2

Listing 2.1 Defining a module (geometry.ex)
defmodule Geometry do             #1
  def rectangle_area(a, b) do     #2
    a * b                         #2
  end                             #2
end                               #3

Shows the minimal defmodule and def structure for a callable Geometry module. section 2.3.1

How Elixir in Action, Third Edition covers it

How deep it goes
Explains definition syntax, naming, imports, aliases, compilation, bytecode loading, and runtime lookup without becoming a full language reference.
Examples
Uses Geometry, Geometry.Rectangle, IO, iex, .ex source files, and compiled .beam files to demonstrate module organization and invocation.
What it assumes
Assumes basic Elixir expressions and functions while teaching module syntax, naming, organization, compilation, and runtime loading.
What you can do after
Build it from scratch using defmodule and def, compile it, load it in iex, and call its functions through qualified or aliased names.
How it connects
Connects modules with functions, namespaces, atoms, BEAM, code paths, Mix, and OTP applications.

Also explained in

Compare how 35 books explain module →

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.