Abstraction of an encapsulted property in Lisp

December 9, 2008

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.

Read the rest of this entry »


Expectation/Mock Framework for Lisp

July 1, 2008

Tonight I just finished writing a nice piece of code. It allows me to create expectations/mock functions. here is an example:

(expect func (1 3) 4)

I started with this as my base line then built my macro for creating a mock function.

‘expect’ is the macro keyword.

‘func’ is the function to be mocked.

‘(1 3)’ is the argument list.

‘4’ is the return value.

Here is the macro with some helper functions:

(defmacro expect (fn-name args ret-val)
  (let ((arg-list (make-symbols args)))
    `(defun ,fn-name ,arg-list
       (let ((expected-args (list ,@args))
             (actual-args (list ,@arg-list)))
         (if (not (equal expected-args actual-args))
             (error (format-expectation-errors expected-args actual-args))
             ,ret-val)))))

(defun format-expectation-errors (expected actual)
  (format nil “Incorrect Expection Args~% Expected: ~S~% Actual: ~S” expected actual))

(defun make-symbols (args)
  (loop for a in args collect (gensym))

The hardest part was to try and get the actual and expected args, but I did it with a little bit of cargo-cultism. evaluation occurs at run-time.

This is not a full blown framework it still need to have some type of controller to keep track of the order of expectations, but that will be for another evening.