I love composition of traits and abstractions like protocols. But I especially love clojure's extend, which allows me to refactor interfaces without having to change the code for the traits.
That's pretty abstract. We obviously need to look at some code. Lets start by looking at two traits. But where before I was defining traits as maps, now I am using records:
(defrecord base [])
(defn new-base [opts]
(let [b (->base)
b (into b opts)
b (assoc b :blap (fn [this] 42))]
b))
(defrecord wackel [])
(defn new-wackel [opts]
(let [w (->wackel)
w (into w opts)
w (assoc w :blip (fn [this x y z] (+ x y z)))]
w))Now here is our story. We have this protocol, gran. It has two methods, where each method is implemented by a different trait:
(defprotocol gran
(blip [this x y z])
(blap [this]))To service this protocol, we create an aggregate, w:
(def w (-> {} new-base new-wackel))
We also extend wackel with the gran protocol:
(extend wackel
gran
{:blip (fn [this x y z]
((:blip this) this x y z))
:blap (fn [this]
((:blap this) this))})Testing this is pretty easy:
(println (blip w 1 2 3)); -> 6
(println (blap w)); -> 42But lets look at what we have achieved.
1. We can add functions to the protocol without changing the traits. We just need to change the aggregate, w.
2. We can move functions from one trait to another, so long as the functions are still defined in the aggregate.
So we have largely decoupled the interface from its implementation. I suspect the ultimate benefit here is a reduction of reuse coupling.
http://programmer.97things.oreilly.com/wiki/index.php/Reuse_Implies_Coupling