Erlang idioms and clean code
| Immutable data | |
| Small functions | |
| Let it crash | |
| Naming rules |
Immutable data
Every value in Erlang is fixed at creation. Code that needs a changed list builds a new one and passes it along.
This removes whole families of bugs: no stale copy, no surprise alias, no lock around shared mutable state.
% build the new list, do not touch the old one
prepend(Item, List) -> [Item | List].
Small functions
A function does one thing and names it. Five lines is a good size, and twenty is a smell.
Small functions give the pattern matcher small pieces to work with, and the compiler small units to warn about.
is_adult(#{age := Age}) -> Age > 18.
% one predicate, one line, no branches
Let it crash
Do not wrap every call in defensive checks. Let the error surface where it happens, and let the supervisor restart the broken part.
The rule sounds reckless and reads clearly: crash loudly in a small scope, recover in a big one.
{ok, User} = fetch_user(UserId).
Naming rules
Variables start uppercase, functions and atoms start lowercase, and modules are all lowercase with underscores. Records and their fields are lowercase too.
The casing is not decoration: it tells the reader what kind of thing every name is, at a glance.
UserName = user_name(UserId).
lists:reverse(UserName).
Next: Rebar3 builds
Article author: Arthur Isaev