Erlang idioms and clean code

The earlier lessons taught the constructs one at a time. This one collects the habits that make an Erlang module easy to read: values that never change, a function per case instead of a nest of case blocks, a crash in a small scope, and names that say what kind of thing they are. None of these is enforced by the compiler; the style checker of the Elvis lesson catches a few of them, and the rest is what a reader trusts.

Immutable data

Every value in Erlang is fixed at creation. Code that needs a changed list builds a new one and passes it along; the old binding keeps the old list. This module prepends an item and prints both lists:

users.erl

-module(users). -export([main/0, prepend/2]). prepend(Item, List) -> [Item | List]. main() -> Old = [2, 3], New = prepend(1, Old), io:format("~p~n", [Old]), io:format("~p~n", [New]).

erlc users.erl

erl -noshell -eval 'users:main(), halt().'

[2,3] [1,2,3]

The new list shares the old tail: the cell that holds 1 points at the existing list [2,3], so a prepend copies nothing. The lists lesson explains that sharing, and the processes lesson shows why a value no process can change needs no lock.

Small functions

A function does one thing and its clauses name the cases. A message handler is the clearest example: each message shape gets one head, so the shape is visible before the body and a wrong message falls to the last clause instead of failing somewhere inside:

handler.erl

-module(handler). -export([main/0, handle/1]). handle({set, Key, Value}) -> {ok, {Key, Value}}; handle({get, Key}) -> {ok, Key}; handle(Other) -> {error, {unknown, Other}}. main() -> io:format("~p~n", [handle({set, port, 8080})]), io:format("~p~n", [handle({get, port})]), io:format("~p~n", [handle(stop)]).

erlc handler.erl

erl -noshell -eval 'handler:main(), halt().'

{ok,{port,8080}} {ok,port} {error,{unknown,stop}}

Each clause is two lines and reads as a sentence: a set message answers the pair, a get message answers the key, and anything else gets an error that names it. A clause that grows past a screen is a sign that one case hides another function; the functions lesson shows the clause syntax itself.

Let it crash

A caller states what it expects with a match and lets the match fail when the expectation is wrong. It does not wrap every call in a defensive check. The shell shows the good match and the failed one:

erl

1> {ok, User} = handler:handle({get, port}). {ok,port} 2> {ok, Missing} = handler:handle(stop). ** exception error: no match of right hand side value {error,{unknown,stop}}

The second line fails at the place that made the wrong assumption, with the value that proved it wrong. In a running system the process dies with that reason, a supervisor restarts it, and the crash report keeps the stacktrace. A handler that instead returns a default and carries on moves the failure to a later line where the cause is gone; the let it crash lesson works the design out with a supervisor.

The nested case

The habit that most often hides a simple function is a nest of case blocks that unpack a tuple with element/2. This module works, and it is the mistake:

nested.erl

-module(nested). -export([main/0, area/1]). area(Shape) -> case is_tuple(Shape) of true -> case element(1, Shape) of square -> element(2, Shape) * element(2, Shape); rectangle -> element(2, Shape) * element(3, Shape) end; false -> error end. main() -> io:format("~p~n", [area({square, 3})]), io:format("~p~n", [area({rectangle, 2, 5})]).

erlc nested.erl

erl -noshell -eval 'nested:main(), halt().'

9 10

The answers are right, and the code is hard to read for two reasons. The shape of the argument is nowhere in the head, so a reader has to follow two branches to learn that a shape is a tagged tuple. And a call with the wrong arity fails inside element/2 with badarg, which names the BIF and not the function that was called with a bad shape. The same function as clauses is one line per shape, and a wrong shape fails with function_clause on nested:area/1:

area({square, Side}) -> Side * Side;
area({rectangle, Width, Height}) -> Width * Height.

The pattern matching in depth lesson names the forms a head can match, and the guards lesson adds the condition after the pattern when a shape alone is not enough.

Naming rules

The casing is part of the syntax, and a reader uses it to tell the kinds of name apart at a glance. A variable starts with an uppercase letter. A function, an atom and a record field start with a lowercase letter. A module is lowercase with underscores, and its file name is the same string. A macro is uppercase.

The underscore has two jobs. A variable named _ is a pattern that matches anything and binds nothing, and a variable such as _Timeout documents an argument the body does not use while still silencing the unused-variable warning. A bare name that is never used fails the build under -Werror, which is why a clause that ignores an argument writes _Other and not Other.

A module name that starts with an uppercase letter is a syntax error, and a file whose name differs from its -module attribute does not compile. Both are the first errors a beginner meets; the first script lesson meets them on purpose.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What happens to a list when you prepend an item?

    Answer

    A new list is built and the old one stays as it was

    Values never change: [Item | List] builds a new list and leaves the original bound value alone.

  2. How long should a function be, according to the lesson?

    Answer

    Five lines is a good size

    A small function does one thing, and the pattern matcher and the compiler work best on small units.

  3. What does "let it crash" mean?

    Answer

    Crash in a small scope and let a supervisor recover the big one

    The failing process dies with a clear reason, and the supervision tree restarts it.

  4. Which name is a variable?

    Answer

    UserName

    Variables start with an uppercase letter; lowercase names are atoms or functions.

  5. What does this module print? -module(q1). -export([main/0]). prepend(Item, List) -> [Item | List]. main() -> Old = [2, 3], New = prepend(1, Old), io:format("~p~n", [Old]), io:format("~p~n", [New]).

    Answer

    [2,3] / [1,2,3]

    The prepend builds a new list; the binding Old keeps the original two items.

  6. What does this module print? -module(q2). -export([main/0]). handle({set, Key, Value}) -> {ok, {Key, Value}}; handle({get, Key}) -> {ok, Key}; handle(Other) -> {error, {unknown, Other}}. main() -> io:format("~p~n", [handle({get, port})]), io:format("~p~n", [handle(stop)]).

    Answer

    {ok,port} / {error,{unknown,stop}}

    The get clause answers the key, and the last clause wraps the unknown term in an error tuple.

  7. What does this module print? -module(q3). -export([main/0]). area({square, Side}) -> Side * Side; area({rectangle, Width, Height}) -> Width * Height. main() -> io:format("~p~n", [area({square, 4})]), io:format("~p~n", [area({rectangle, 2, 3})]).

    Answer

    16 / 6

    The square clause multiplies 4 by 4, and the rectangle clause multiplies 2 by 3.

  8. Why is the clause version of area/1 better than the nested case?

    Answer

    The shape of each argument is visible in the head

    A head per shape reads like a type, and a wrong shape fails with function_clause on the function itself.

  9. What does this module print? -module(q4). -export([main/0]). main() -> User = #{name => "Ada", age => 36}, Older = User#{age => 37}, io:format("~p~n", [maps:get(age, User)]), io:format("~p~n", [maps:get(age, Older)]).

    Answer

    36 / 37

    The update builds a new map; the binding User keeps age 36 and Older holds 37.

  10. Why is immutability a gift for concurrent code?

    Answer

    No shared value can change under another process

    With no shared mutable state there is no lock to take and no stale copy to guard against.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev