On Apr 19, 11:00 am, Timo Mihaljov <noid....@gmail.com> wrote:
> I'm wondering about how to change a data structure without breaking the
> API used to access it. For example, let's assume that I have a library
> for dealing with records of people and I'm storing them in structs.
>
>      (defstruct person :name)
>
> The users of my library access the data stored in the records like any
> other map.
>
>      (:name some-person)
>
> When the library's been in use for a while, I realize that I need to
> make a change to the data structure.
>
>      (defstruct :first-name :last-name)
>
> The problem is that making this change would break all the clients using
> the library.


I won't claim this is an elegant solution, but it's similar in spirit
to your Python example:

;; Original definition of person
(defn person [record]
  (fn
    ([key] (key record))
    ([key value] (person (assoc record key value)))))

(def p1 (person {:name "Stuart Sierra"}))

(p1 :name)
;;=> "Stuart Sierra"

;; Now change the definition of person.
(defn person [record]
  (fn
    ([key]
       (if (= key :name)
         (str (:first-name record) " " (:last-name record))
         (key record)))
    ([key value]
       (if (= key :name)
         (throw (Exception. ":name cannot be set any more"))
         (person (assoc record key value))))))

(def p2 (person {:first-name "Stuart" :last-name "Sierra"}))

(p2 :name)
;;=> "Stuart Sierra"

(def p3 (p2 :last-name "Halloway"))

(p3 :name)
;;=> "Stuart Halloway"


-Stuart Sierra
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to