Debugging in Clojure · Dave Martin's Blog

submited by
Style Pass
2021-07-06 17:00:06

Whenever I speak to other Clojure developers, whether they’re seasoned pros or brand new to the language, one question that always comes up is “how do you debug your code?”. Most of us have heard the rhetoric around REPL driven development - “develop your program interactively in the REPL, debugging as you go!”. This sounds straightforward, but it’s often not quite that easy in practice. Say you’re writing a REST API using Compojure, and you notice one of your endpoints is returning an incorrect response. How do you go about debugging it? In this case it’s not as easy as “construct a map in the repl, pass it to your function, and see if the output is what you expect”. You may not know what the request map looks like, and mutable state also gets in the way - things like database connections, Kafka consumers, and HTTP servers. In this guide, I’ll detail my personal approach debugging in situations like this.

When I find a bug, often the first thing I do is good ol’ fashioned println debugging. It may be primitive, but it’s often the quickest way to diagnose the problem! In other languages, it can be a bit awkward trying to shoehorn console.log statements into your code. Luckily, Clojure’s reader tags come in handy here. I’m a big fan of the spyscope library, which exploits reader tags to full effect. It’s dead simple - once you’ve installed it as per the readme, just put #spy/p in front of the form you want to print out. It’s my go-to library for easily pretty-printing values to the REPL. When that code is executed, it’ll print the result of the form to the REPL, with nice colours to boot! This is great for quickly seeing what a form evaluates to, which is often all you need to diagnose the problem.

Leave a Comment