Abstraction of an encapsulted property in Lisp

Abstraction (computer science): is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.

If you read Lisp Trick #1, hopefully, you saw a pretty good abstraction. What it was doing was abstracting out the setting and getting a value from a variable. As a bonus, because of the way &key parameter keyword can be used, we were able to differentiate whether you were getting the value or setting the variable. Another bonus is that the variable we are getting and setting is encapsulated.

Usually an abstraction is created with the use of macros. Now I’ve made an even larger abstraction of the setter/getter abstraction.

Here it is:

(defmacro with-property (property &body body)
  (when property
    (let ((p-n (first property)))
      `(let ((,@property))
         (defun ,p-n (&key (is nil is-p))
             (is-p (setf ,p-n is))
             (t ,p-n)))

       (assert-equal nil (with-property nil)))

       (assert-equal 1 (with-property (value 1) value))
       (unintern 'value))

       (with-property (value 1)
         (value :is 12))
       (assert-equal 12 (value))
       (value :is 24)
       (assert-equal 24 (value))
       (unintern 'value))

       (let ((property 'property))
         (with-property (property 8) property)
         (assert-equal 8 (property)))
       (assert-equal 8 (property))
       (unintern 'property)))

You’ll notice that the scope for the variable remains even after leaving the ‘with-property’ abstraction. Right now I don’t know if that is good or bad. We’ll see.

NOTE: You need to review “And Behind Door Number 2 Is . . .” for an explanation of why this has a leaky abstraction.


One Response to Abstraction of an encapsulted property in Lisp

  1. Zach Beane says:

    Trick #1 is bogus, and this piles on more bogus.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: