Search code examples
lispcommon-lispclos

Common Lisp Object System method execution order


I have the following two classes:

(defclass person () ())

(defmethod speak ((s person) string)
    (format t "-A" string))

(defmethod speak :before ((s person) string)
    (print "Hello! "))

(defmethod speak :after ((s person) string)
    (print "Have a nice day!"))


(defclass speaker (person) ())

(defmethod speak ((i speaker) string)
  (print "Bonjour!"))


(speak (make-instance 'speaker) "Can I help yoU?")

And the ouput of this is:

"Hello! "                                                                                                                                                                                                                                               
"Bonjour!"                                                                                                                                                                                                                                              
"Have a nice day!" 

What I'm trying to figure out is how these methods are executed in terms of "order." I cannot seem to grasp on what is happening and why. Supposedly there is a rule precedence to this but I'm not sure where to find it. For example, why doesn't "Hello!Can I help you" ever fire in this case?


Solution

  • When you don't have any around methods, the order of method application is: all before methods from most specific to least specific, then the most specific primary method, and then the after methods from least specific to most specific. In your case you have two primary methods (methods without :before or :after next to the name), one which specifies on person, and the other which specifies on speaker. Since speaker is more specific than person, only the speaker primary method is called. If you want to call multiple primary methods, look at call-next-method.