When I'm going to swap!
the value of an atom conditionally, should the condition wrap the swap!
or should it be part of the function swap!
calls?
(import '(java.time Instant))
(def not-nil? (comp not nil?))
(defonce users (atom {
"example user 1" {:ts (Instant/now)}
"example user 2" {:ts (Instant/now)}
}))
(defn update-ts [id]
(if (not-nil? (get @users id))
(swap! users assoc-in [id :ts] (Instant/now))))
In the above example, I'm doing the existence check for the user before doing the swap!
. But couldn't the user be deleted from users
after the check but before the swap!
? So, then, is it safer to put the check inside the function run by swap!
?
(defn update-ts [id]
(swap! users (fn [users]
(if (not-nil? (get users id))
(assoc-in users [id :ts] (Instant/now))
users))))