We wanted to know what Joe Armstrong actually did when he sat down at home to write Erlang. How long were his functions? What went in a module? When did he reach for a process?
The answer starts with a pencil
. That caught my eye. I’ve written before about thinking on paper, and here was one of the people who invented Erlang describing much the same thing. He drew, took notes, and wrote little programs to answer questions he couldn’t settle on paper
. Once he understood the problem, he could sit down and write. For hard compiler work, he would stay home, leave email alone, and give himself four uninterrupted hours. notes on writing by hand · Armstrong in Coders at Work, pp. 215–231
Paper, Emacs, shell
At home he had a 15-inch MacBook Pro. He wrote in Emacs, built with Make and Bash, and debugged with print statements. He used Git and Subversion. His advice to a beginner was to open a text editor and an Erlang shell. Type a small program yourself. Compile it with c(module). and call a function. Change something and do it again. Learn what the build tool automates before you ask it to do the work. (Joe’s desk and tools, Joe’s mailing list post, Erlang shell manual)
He liked to tackle the hardest part of a design first. If he needed to find out whether an idea would work, he built a prototype for that part. He also learned to stop when he was too tired to see his way through the code. He knew how much of it he would throw away in the morning. (Coders at Work, pp. 215–216 and 231)
There are two tempos here. Take your time figuring out what the program should do. Then get quick feedback on each small piece you write. Great distinction. You can spend a morning on the design and still want the distance from the editor to a running function to be about three keystrokes.
400 lines. 20 lines. 80 columns.
In 1996 Armstrong, K. Eriksson, and M. Williams wrote an Ericsson guide called Program Development Using Erlang. Armstrong reproduced it in Appendix B of his thesis. The numbers are from that guide. I’d use them as prompts to reread my code. Ericsson guide, §§3, 6–8 · Armstrong’s thesis, Appendix B, printed p. 215
- 400 lines to a module. Keep related functions together. A library for lists has a clear subject. A library for lists and math is already on its way to becoming a junk drawer.
- 15–20 lines to a function. When a function gets long, look for a step you can give a good name.
- 80 characters to a line. The guide gives a wonderfully practical reason. The code should fit on a sheet of A4.
- Two levels of indentation for most code. Watch for a
caseinside areceiveinside anothercase. Extract the operation you actually want to name. - Keep exports few. A reader should be able to get the shape of a module from its
-exportlist. The guide suggests grouping and labeling exports when they serve different audiences. - Keep dependencies few and acyclic. Prefer
module:function(...)over-importso the reader can see where a call goes. Give related modules a shared prefix when it helps. - Make names and layout predictable. An
is_...function should answer yes or no. Acheck_...function can return details about what it found. Use one formatting style across the project.
Write the call you want to read
Armstrong called this intentional programming. His example is a dictionary. The actual work in all three calls is looking up a key. What the caller means is different.
dict:fetch(Key, Dict)says the key is supposed to be there.dict:find(Key, Dict)says the key may be absent. Handle either result.dict:is_key(Key, Dict)asks a yes-or-no question.
He used the name search in the thesis. The standard module calls that operation find/2. The point survives the name change. I can read the call and tell which assumption the programmer made. Thesis, §4.5 · The dict API
The same goes for data. If a queue happens to be a list today, give the caller queue:new() and queue:len(Q). Tomorrow the queue can become two lists and the callers can go about their business. Start with the operations the caller needs. Use tagged results such as {ok, Value} and {error, Reason} when a caller must distinguish outcomes. Pass state as an argument when you can. Keep I/O and other side effects in a few places you can find again. Get the straightforward version working before you try to make it fast. Ericsson guide, §§3.3–3.13 and 6.3–6.5
Here is a small example I’d try in the shell. A chat room can decline an empty message. That’s an ordinary outcome.
-module(room).
-export([post/3]).
post(_Name, <<>>, _Messages) ->
{error, empty_message};
post(Name, Text, Messages) when is_binary(Text) ->
{ok, [{Name, Text} | Messages]}.
Save it as room.erl and run erl in that directory.
1> c(room).
{ok,room}
2> room:post(alex, <<"hello">>, []).
{ok,[{alex,<<"hello">>}]}
3> room:post(alex, <<>>, []).
{error,empty_message}
That’s the rule for posting a message. You can read it, run it, and change it as a function. A process can own the room’s state when there are several people talking to it.
Give each process a job
Armstrong wanted the shape of the program to follow the shape of the problem. A chat room, a connection to it, and a supervisor can each have a job. Formatting a message can be a function call. In the thesis he walks through a small location register. One module handles sending, receiving, and running the server. The other contains the rules for storing and looking up a location. The program that knows what a location means can stay sequential. Thesis, §4.1 · OTP design principles and their small server example · gen_server
The old guide has good advice for the day you do write a receive loop. Keep the main loop in one module. Give each type of message a tag. Make the loop tail recursive. Decide what to do with unexpected messages, and remember that a reply can arrive after its timeout. Ericsson guide, §5
Check external data when it enters. Give expected failures an ordinary return value. When an internal assumption breaks and a worker can’t do its job, let the worker fail and give another process responsibility for recovery. Decide what state must survive a restart. Keep enough detail in the log to find the fault later, and give the person using the program a message they can act on. Thesis, §§4.3–4.5 · OTP supervisor guide · Armstrong on error messages
Write down the problem
Armstrong once wrote several pages of comments to explain a tricky part of a program. Someone took the comments out. He brought up that deletion when an interviewer asked about the worst mistakes he’d seen in Erlang code. I understand why. When I come back to a program, I can usually work out what it does. The hard part is recovering what I was trying to do. For a function, write down what goes in, what comes out, and what can fail. For code that implements a protocol, link to the specification. Michael Suess’s interview · Ericsson guide, §8
More to read and try
- My Favorite Erlang Program. Armstrong writes a process that waits for a function, then runs it. The whole example and shell session fit on one page.
- Minimal Viable Programs. Peter Högfeldt’s bug tracker consisted of a shell command, text files, and version control. Armstrong explains why he liked it.
- Connecting Erlang to Sonic Pi and Controlling Sound with OSC Messages. Two examples of what he built when he was curious about something.
- Programming Erlang, second edition. Look for “The Road to the Generic Server” and the IRC Lite example. Free concurrency chapter (PDF) · Book source code (ZIP)
- Armstrong’s personal web notebook and his GitHub. Start with the small programs.
I want to try this on a little chat server at home. First, write down the rules of a room. Then make them work in the shell. Give the room a process when there’s someone else to talk to.