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)) (cond (is-p (setf ,p-n is)) (t ,p-n))) ,@body)))) (test-fixture :with-property-macro (:tests (should-single-nil-property (assert-equal nil (with-property nil))) (should-single-property (assert-equal 1 (with-property (value 1) value)) (unintern 'value)) (should-use-property (with-property (value 1) (value :is 12)) (assert-equal 12 (value)) (value :is 24) (assert-equal 24 (value)) (unintern 'value)) (should-not-capture-property (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.