When and Where to Use Macros

Because Elixir is a language built on top of macros, it’s easy to think that every library you write needs macros. This isn’t the case. Macros should be reserved for specialized cases where the solution can’t be implemented easily as normal function definitions. Whenever you’re writing code and reach for defmacro, stop and ask yourself whether your solution requires code generation. Sometimes code generation is absolutely required, but other times it’s easy to get carried away with macros where you could’ve just written functions instead.

In some cases, the choice for macros is easy. For things like control flow, where access to the AST expression is required, macros are the obvious choice. For example, let’s imagine ...

Get Metaprogramming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.