Reducing Reuse Coupling

97 views
Skip to first unread message

William la Forge

unread,
Nov 24, 2015, 12:45:57 PM11/24/15
to Clojure
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)); -> 42


But 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


William la Forge

unread,
Nov 24, 2015, 12:50:04 PM11/24/15
to Clojure

William la Forge

unread,
Nov 24, 2015, 3:51:47 PM11/24/15
to Clojure
For greater clarity, I've cleaned up the code and broken it into 2 files, record-play0 and record-play:

(ns aatree.record-play0)

(set! *warn-on-reflection* true)


(defrecord base [])

(defn new-base [opts]
  (-> (->base)
(into opts)
(assoc :blap (fn [this] 42))))


(defrecord wackel [])

(defn new-wackel [opts]
  (-> (->wackel)
(into opts)
(assoc :blip (fn [this x y z] (+ x y z)))))

---

(ns aatree.record-play
(:require [aatree.record-play0 :refer :all]))

(set! *warn-on-reflection* true)


(defprotocol gran
(blip [this x y z])
(blap [this]))

(def w (-> {} new-base new-wackel))

(extend-type aatree.record_play0.wackel

gran
(blip [this x y z]
    ((:blip this) this x y z))
  (blap [this]
((:blap this) this)))


(def w (-> {} new-base new-wackel))

Reply all
Reply to author
Forward
0 new messages