Chapter 4
Evaluate Code in Context

So far you’ve seen the building blocks for writing macros, and you’ve learned why they aren’t the ideal solution for every problem. In the remainder of this book, we’ll look at several broad categories of macros to learn how you can clarify your code’s intentions, add your own control flow mechanisms, and take advantage of your other macro superpowers.

In this chapter, you’ll see macros that wrap the code they’re given into a new context for evaluating them. For example, you might want to evaluate a given expression with dynamic bindings, within a try/catch block, or where a resource is opened and then cleaned up. In this category of macros, you’re not doing anything too fancy with the input expressions—they’re simply wrapped with some logic that you want to abstract away from the caller. You’ll see some ways to get rid of hard-to-remove structural duplication like the following example, where the small bit of code that varies ([INFO] vs. [ERROR]) is surrounded by a bunch of code that’s duplicated from one function to the next:

context/structural_duplication.clj
 
(​require​ '[clojure.java.io :as io])
 
(​defn​ info-to-file [path text]
 
(​let​ [file (io/writer path :append true)]
 
(​try
 
(​binding​ [*out* file]
 
(​println​ ​"[INFO]"​ text))
 
(finally
 
(​.​close file)))))
 
 
(​defn​ error-to-file [path text]
 
(​let​ [file (io/writer path :append true)]
 
(​try
 
(​binding​ [*out* file]
 
(​println​ ​"[ERROR]"​ text))
 
(finally
 
(​.​close file)))))

Does this kind of duplication make your programmer code-senses tingle? It sure does for me. We’ve got the things that change all mixed up with the things that stay the same, so it’s easy to lose sight of what’s important. In this chapter, we’ll see how to strip away the boilerplate code and leave only what’s necessary. And as we go, we’ll build upon the work we started in the previous chapter to develop a sense of how to accomplish some of these same goals with functions.

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

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