...

/

When and Where to Use Macros

When and Where to Use Macros

Learn the tips and tricks for the correct use of macros.

We’ve unlocked many of Elixir’s metaprogramming secrets. We went from the basics to writing our own language features. Along the way, we gained insight into Elixir’s internals and probably found a new appreciation for the language’s syntax and idioms. Without curbing the excitement, we’re going to review some tips and tricks for getting the most out of Elixir’s macro system and avoiding common pitfalls. Staying on the happy path of metaprogramming will let us write extensible code, which is easy to write and maintain.

The trial terminal

Use the following terminal to try and execute the commands given in the lesson:

Terminal 1
Terminal
Loading...

The correct use of macros

Elixir is a language built on top of macros, so it’s easy to think that every library 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 writing code and reaching for defmacro, stop and ask whether the solution requires code generation. Sometimes, code generation is required, but other times writing functions works better. i So, don’t get too carried away with macros.

In some cases, the choice for macros is easy. ...