Sunday, 15 April 2012

oop - Mapping an objected oriented model to Clojure -



oop - Mapping an objected oriented model to Clojure -

say working in object oriented language , there 2 classes x , y , there bidirectional relationship between classes.

so instance of x can point instance of y , vice versa.

in clojure classes translate maps, have:

{:type :x :name "instance of x"} {:type :y :name "instance of y"}

how represent bidirectional relationship between these "objects", without using "foreign keys"? or straight delegated database?

it's pretty mutual see deeply-nested maps in clojure correspond hierarchical object trees in object-oriented languages, e.g.

{:type :x :name "instance of x" :y {:type :y :name "instance of y"}}

in fact, mutual clojure.core provides core functions get-in, assoc-in, , update-in facilitate working such structures.

of course, works best when there's natural hierarchy or ownership relationship between objects beingness modeled. in case of cyclical references construction breaks downwards (assuming you're sticking persistent info structures) -- see why, seek constructing clojure map contains value.

the way i've typically seen dealt introduce layer of indirection using atom:

(def x {:type :x, :name "x instance", :y (atom nil)}) (def y {:type :y, :name "y instance", :x (atom nil)}) (set! *print-level* 3) ;; in repl avoid stack overflow ;; when printing results of next calls (reset! (:y x) y) (reset! (:x y) x)

oop clojure

No comments:

Post a Comment