The Module Behind the Curtain

spapiernik

spapiernik

5 hours ago

0 comments

Use defdelegate when a function should simply forward its arguments to another module.

defmodule Users do
  defdelegate get(id), to: Accounts
end

This is equivalent to writing:

defmodule Users do
  def get(id), do: Accounts.get(id)
end

defdelegate is useful when you want to expose a function through a public API without duplicating its implementation.

You can also rename the delegated function:

defmodule User do
  defdelegate find_user(id), to: Accounts, as: :get
end

This calls Accounts.get(id) when Users.find_user(id) is invoked.

A good rule of thumb: use defdelegate when the function exists purely as a forwarding layer; if you need additional logic, define the function normally.

Comments (0)

Sign in with GitHub to join the discussion