Experience in Clojure develops steadily – incompetence still prevails

I’m developing a security layer for the librarian-clojure project and stumbled upon an issue that I could hardly diagnose. Ultimately it turned out not a complicated issue which however took me almost a day to sort out. Incompetence prevailed.

Have a look at the following code and try to figure out why the result is nil, although 3 is the key for a map in the *sessions* map.

(def ^:dynamic *sessions* (atom {}))

(defn get-data-from-session [sid]
  "Retrieve data from the session sid"
  (@*sessions* sid))

(defn set-data-in-session [sid data]
  "Set data in the session sid"
  (swap! *sessions*
         (fn [m] (conj m {sid data}))))

Here goes the interactive session in Clojure’s REPL.

user=> @*sessions*
{3 {:a 1}}

user=> (def uri "/sessions/3")

user=> (nth (.split uri "/") 2)

user=> (get-data-from-session
         (nth (.split uri "/") 2))

Nil?! Why?! Solution is so simple yet it took me almost a day to find it out! Would you believe it?! I wish I didn’t.

The result of the function nth‘s call is of String type whereas the key in the *sessions* map was of Integer type. The different types made the task longer than I wished it’d had. Another lesson’s learnt.

Be Sociable, Share!
This entry was posted in Languages.

6 Responses to Experience in Clojure develops steadily – incompetence still prevails

  1. Static typing catch such bugs before they surface.

    • I did expect such responses, and am glad I didn’t have to wait long. Thanks!

      It’s not a bug as it didn’t work when I interactively developed and tested the solution. I couldn’t do that in Java and hence I’m happy with what Clojure REPL provides. In this case a static type system is as much useful as test-first development and I’d rather choose the former as a recipe for success.

      • Clojure is optionally typed AFAIK

        • You can specify a type of a symbol, but it’s rarely used and I wouldn’t be surprised to be told it’d not be an idiomatic code.

          To me, type system is just a preliminary check as the other checks/tests you might be writing yourself. It’s useful, but might be hard to get right and hence abused.

          With that said, I can accept the claim that a statically typed language would prevent this issue from happening, but on the other hand would hinder other goodies too (less typing is what springs to my mind atm and can understand is not always useful).

  2. The Clojure books I’ve read for the most part are all well written, but there needs to be a guide on how you’re really supposed to do things, like — as I have been told — avoid loop .. recur, rely on sequences wherever possible, and avoid nth. This was a helpful post and might explain why one of my text key searches for comparison did not return what I expected.

Leave a Reply

%d bloggers like this: