How to fix common elixir programming mistakes

Most beginner Elixir errors are not exotic. They come from a handful of habits: treating = as assignment, forgetting that data is immutable, binding variables inside a match you thought was an assignment, and reaching for a process when a plain function would do. Recognising four or five of these patterns will clear most of your red terminal output.

“Match error” and the equals sign

An error like ** (MatchError) no match of right hand side value means the left side was a pattern that did not fit the right side. If you wrote {:ok, result} = some_call() and the call returned :error, nothing is wrong with the code — the pattern was honest and the value did not match.

The fix is usually to handle both shapes explicitly with a case or two function clauses. When you genuinely do not care about the shape, use _ on the left instead of a variable you never read.

Immutability isn’t a bug

Newcomers write list = Enum.map(list, fun) expecting the original to change, then wonder why a value further down is stale. Elixir rebinds the name; it never mutates the data. Every transformation returns a new value, and you must thread that value forward.

The same mistake appears with maps. Map.put(map, :key, 1) returns a new map. If you ignore the return value, nothing happened. Any function whose result you drop is a no-op, and the compiler will not always warn you.

Silent nils from square brackets

map[:missing] returns nil instead of raising. That is convenient until a nil travels three functions deep and surfaces as a confusing error far from its source. Match the key you expect — %{name: name} = map — when the key must be present, and use Map.get with a default when it may be absent.

  • Expect the key: pattern match.
  • Key may be missing: Map.get(map, :key, default).
  • Key must exist, crash is acceptable: Map.fetch!.

Processes and branches where a function would do

If your module has one GenServer whose only job is to return a value from a map, you have added a mailbox and a timeout to a lookup. Ask what state the process protects. If the answer is “a value I could pass as an argument”, delete the process. Keep it when the state must outlive a single call.

Long cond blocks with two branches that check the same variable are a sign the function wants to be split into clauses. The same goes for a case whose branches each return a differently shaped value. Decide what every branch returns before you write any of them, and the shape of the code becomes obvious.

Debug by shrinking the input

When the error makes no sense, copy the smallest input that reproduces it into iex and call each step by hand. Add IO.inspect with a label, not bare inspect calls. Nine times out of ten the value you assumed was a list is a map, or the string still has a trailing newline from a file read.

Fix one thing, run the tests, then look again. Changing three things at once is how a fix becomes two new bugs.