Elixir Conventions
Control Flow
- •Prefer
withchains over nestedcase. - •Use
Enum.reduce_whileorEnum.flat_mapoverEnum.reducewith internal conditionals. - •Pattern match in function heads rather than branching in the body.
Types & Structs
- •Use
typedstructfor struct definitions. - •Startup arguments use a
startup_optionsunion type:elixir@type startup_options :: {:node_id, String.t()} | {:id, atom()} @spec start_link(list(startup_options())) :: GenServer.on_start() - •Keep type definitions near the top, after
use/aliasblocks.
GenServer / CQRS
- •
callfor reads or synchronization only. Writes usecast. - •
handle_callbody:{:reply, do_foo(...), state}— core logic in thedo_function. - •Never call a callback from another callback.
- •Actor modules require three sections:
elixir
############################################################ # Public RPC API # ############################################################ ############################################################ # GenServer Behavior # ############################################################ ############################################################ # GenServer Implementation # ############################################################
Documentation
- •First-person voice: "I am the X module." / "I return the Y."
- •
@moduledocstarts with one-sentence purpose. - •
### Public APIsection listing all public functions. - •All public functions need
@docand@spec.
Examples
- •Live in
lib/examples/e_<module>.ex. - •Module name pattern:
E<Module>(e.g.,ENode,EShard). - •Use
import ExUnit.Assertionsforassert.
Interactive Testing
- •Run one-off expressions:
timeout 60 mix run -e 'code'(never use--no-halt, it hangs the VM). - •Inspect process state:
:sys.get_state(pid) - •Query Mnesia:
elixir
:mnesia.transaction(fn -> :mnesia.match_object({table, :_, :_}) end)
Formatting
- •78 character line length.
- •Run
mix formatbefore finalizing. - •Section headers use banner comments:
elixir
############################################################ # Section Name # ############################################################