When to Use Macros

In 1996, author Chuck Palahniuk released the novel “Fight Club”, which was later made into a movie. The so-called fight club in the story had a set of rules. The first rule of fight club was, "You don’t talk about fight club."

In a similar spirit, we introduce Macro Club. Macro Club has two rules, plus one exception. The first rule of Macro Club is Don’t Write Macros. Macros are complex, and they require you to think carefully about the interplay of macro expansion time and compile time. If you can write it as a function, think twice before using a macro.

The second rule of Macro Club is Write Macros If That Is the Only Way to Encapsulate a Pattern. All programming languages provide some way to encapsulate patterns, but without macros these mechanisms are incomplete. In most languages, you sense that incompleteness whenever you say, “My life would be easier if only my language had feature X.” In Clojure, you just implement feature X using a macro.

The exception to the rule is that you can write any macro that makes life easier for your callers when compared with an equivalent function. But to understand this exception, you need some practice writing macros and comparing them to functions. So, let’s get started with an example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.164.75