It seems that I learn something new about Common Lisp just about every day. As I learn more about Common Lisp, I often cringe at some hack that I've employed in my code as a result of my ignorance. I'd like this topic to be a place for people to post their lesson of the day.
Today's lesson relates to using the CLOS and constructor functions. As recommended in Keene[1], I like to define constructor functions for objects of the form make-foo. Then I can enforce mandatory and optional INITARGs for making an instance of the object. Plus, I can hide construction of the object behind an API. I've struggled in the past with how to properly pass the optional INITARGS to MAKE-INSTANCE. This week I had a requirement for using the &ALLOW-OTHER-KEYS lambda list argument. While reading through Section 3.4.1 of the Hyperspec, it suddenly struck me how to properly pass the optional INITARGS to MAKE-INSTANCE.
Cheers,
~ Tom
[1] Sonja E. Keen, "Object-Oriented Programming in Common Lisp", Addison-Wesley, 1989.
Today's lesson relates to using the CLOS and constructor functions. As recommended in Keene[1], I like to define constructor functions for objects of the form make-foo. Then I can enforce mandatory and optional INITARGs for making an instance of the object. Plus, I can hide construction of the object behind an API. I've struggled in the past with how to properly pass the optional INITARGS to MAKE-INSTANCE. This week I had a requirement for using the &ALLOW-OTHER-KEYS lambda list argument. While reading through Section 3.4.1 of the Hyperspec, it suddenly struck me how to properly pass the optional INITARGS to MAKE-INSTANCE.
(defclass scratch-object ()
((mandatory1
:initarg :mandatory1
:accessor mandatory1)
(mandatory2
:initarg :mandatory2
:accessor mandatory2)
(option1
:initarg :option1
:accessor option1)
(option2
:initarg :option2
:accessor option2)
(option3
:initarg :option3
:accessor option3))
(:default-initargs
:option1 "Option 1"
:option2 "Option 2"
:option3 "Option 3")
(:documentation
"A scratch object for testing concepts."))
(defun make-scratch-object (mandatory1 mandatory2
&rest all-keys
&key option1 option2 option3)
"Return a new instance of a scratch object."
(apply #'make-instance
'scratch-object
:mandatory1 mandatory1
:mandatory2 mandatory2
all-keys))
This constructor will properly handle the mandatory and optional INITARGS and will also check the keywords. That was my Common Lisp lesson of the day.Cheers,
~ Tom
[1] Sonja E. Keen, "Object-Oriented Programming in Common Lisp", Addison-Wesley, 1989.
Thomas M. Hermann
Odonata Research LLC
http://www.odonata-research.com/
http://www.linkedin.com/in/thomasmhermann
Odonata Research LLC
http://www.odonata-research.com/
http://www.linkedin.com/in/thomasmhermann