liveBook · Manning

Def macro

As explained in Elixir in Action, Third Edition

The def macro is an Elixir compile-time macro that defines a named function from its name, arguments, and body.

The def macro defines a named function inside a module from its name, argument list, and body. Functions return the value of their last expression, without an explicit return. section 2.3.2

Use def with these practical conventions:

  • Name functions with lowercase letters or underscores; use ? for boolean-oriented names and ! for functions that may raise errors. section 2.3.2
  • Omit parentheses for zero-argument functions, and use the condensed one-line form when the body has one expression. section 2.3.2
  • Define public functions with def; use defp when a helper must remain private to its module. section 2.3.4

Public and private functions

A module can export double while hiding its sum helper: def double(a) do sum(a, a) end; defp sum(a, b) do a + b end. TestPrivate.double(3) returns 6, while calling TestPrivate.sum(3, 4) fails. section 2.3.4

defmodule Geometry do
  def rectangle_area(a, b) do    #1
    ...                          #2
  end
end

A minimal module shows the required relationship between def, a function name, arguments, and a do...end body. section 2.3.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains definition syntax, return-by-last-expression, shorthand forms, and visibility, but def macro expansion remains deferred.
Examples
Uses Geometry.rectangle_area for syntax and TestPrivate.double with a private sum helper for visibility.
What it assumes
Assumes basic modules and expressions while teaching function syntax and last-expression return behavior.
What you can do after
Build it from scratch by defining public module functions and selecting private helpers with defp.
How it connects
Connects modules, functions, expressions, macros, and private functions.

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.