jonnifyelixir
F3 / F3.03 / organising

F3.03 · part 2 of 3

Organising with modules

A module is declared with defmodule and groups related functions under one name. Inside it, three facilities keep code tidy: module attributes hold compile-time constants, alias shortens a long module name, and import pulls another module’s functions into scope so you can call them without a prefix.

Building up the Portal module: a pass-mark constant, an alias for a nested report module, and an import that drops a prefix. Select a facility to see what it changes.

The Portal module

Everything below lives inside defmodule Portal do … end. Attributes, aliases, and imports are directives that shape how the functions are written and called. Select one to highlight it.

The facility · select one

defmodule Portal do @pass_mark 60 alias Portal.Report import Integer, only: [is_even: 1] def grade(score), do: ... end

      

role: a compile-time constant

effect: @pass_mark 60 — one value, fixed at compile time

A module is more than a bag of functions: attributes give it constants, and alias and import control how its neighbours’ names appear. Together they keep call sites short without hiding where a function comes from.

Documentation & structure

Two more attributes are special: @moduledoc documents the module and @doc documents the function beneath it, both readable in IEx with h Portal and compiled into HTML docs. The convention is one module per file, named to match — Portal.Report lives in portal/report.ex — and modules nest by dotting the name, which is purely organisational, not containment.

defmodule Portal do
  @moduledoc "Scoring and grading for the learning portal."
  @pass_mark 60

  @doc "Grades an average score into :a, :b, or :c."
  def grade(avg), do: ...
end

defmodule Portal.Report do   # nested name, own file: portal/report.ex
  def render(grades), do: ...
end

F3.03.1 · functions, defined

Named clauses that take values and return values.

F3.03.2 · modules name where they live

One namespace per concern; @attributes, alias, and import organise the rest.

Next: the pipe operator — how |> composes these module functions into a single readable pipeline.

References

Primary sources for this lesson, and where it connects in the course.