Choose Wisely

Sometimes—especially for the newly arrived Clojure programmer—it can be difficult to know which container to reach for in any given situation. After all, along with vars we now have atoms and refs and agents. It is an embarrassment of programming riches. Fortunately there are some straightforward guidelines that you can follow.

The first rule: If your value is mostly stable over the life of the program, perhaps with some thread-local variations, then put it in a var.

The second rule: If you have a number of mutable values that need to be updated together—and those updates don’t involve side effects—then use refs. Remember, it’s refs that give you that databaselike ability to build transactions.

The third rule: If there are side ...

Get Getting Clojure 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.