Avoiding Common Pitfalls
Let's learn a few common mistakes that we should always avoid.
We'll cover the following...
Elixir is a powerful tool, but you’ll need to be careful.There are a few common mistakes that can wreak havoc on our codebase over time if ignored. Let’s find out ways to avoid getting caught in the web of code generation.
Don’t rely on use
One of the most common mistakes newly minted meta-programmers make is treating use
as a way to mix in functions from other modules. This tempting idea conflates the concept of a mix-in from other languages, where we can introduce methods and functions from one module into another. In Elixir, this pitfall looks something like this:
Consider a StringTransforms
module that defines a number of string transformation functions to use around our codebase. We might write something like this for easy sharing across different modules:
defmodule StringTransforms do defmacro __using__(_opts) do quote do def title_case(str) do str |> String.split(" ") |> Enum.map(fn <<first::utf8, rest::binary>> -> String.upcase(List.to_string([first])) <> rest end) |> Enum.join(" ") end def dash_case(str) do str |> String.downcase |> String.replace(~r/[^\w]/, "-") end # ... hundreds of more lines of string transform functions end end end defmodule User do use StringTransforms def friendly_id(user) do dash_case(user.name) end end
Execute the following commands to run the code:
iex> c "String_Transforms.exs"
iex> User.friendly_id(%{name: "Elixir Lang"})
# Output: "elixir-lang"
...