wrapper - How to encapsulate in clojure? -
i have clojure code looks this:
(defn rect [x y w h] {:x x, :y y, :w w, :h h}) (def left :x) (def top :y) (def width :w) (def height :h) (defn right [r] (+ (left r) (width r))) (defn bottom [r] (+ (top r) (height r)))
now following code seems bit uncommon:
(def left :x)
however don't know other way encapsulation.
suppose, later want represent rect different way. relying on (:x rect) not idea, because :x works on hashmap's , records, leaking implementation details in api, @ least in oo languages considered bad practice.
now, if decide implement rect in java instead, gets worse, because have write wrappers like:
(defn left [rect] (.getleft rect))
to make sure interface doesn't change.
how clojure around problem?
you can use protocols.
first clojure record:
(defprotocol rectangular (left [this]) (right [this])) (defrecord rect [x y w h] rectangular (left [this] x) (right [this] (+ x w))) (def my-rect (rect. 1 2 3 4)) (right my-rect) ;=> 4
now java object:
(import java.awt.rectangle) (extend-type rectangle rectangular (left [this] (int (.getx this))) (right [this] (int (+ (.getx this) (.getwidth this))))) (def my-other-rect (rectangle. 1 2 3 4)) (right my-other-rect) ;=> 4
Comments
Post a Comment