Skip to content

Instantly share code, notes, and snippets.

@wsgac
Last active October 21, 2025 20:56
Show Gist options
  • Select an option

  • Save wsgac/fe5c668e93330ed32e0f996789675bf8 to your computer and use it in GitHub Desktop.

Select an option

Save wsgac/fe5c668e93330ed32e0f996789675bf8 to your computer and use it in GitHub Desktop.
Commutative CLOS mixins demo
(defvar level)
(defclass setup-mixin () ())
(defmethod run :around ((m setup-mixin))
(let ((level 0))
(call-next-method)))
(defclass mixin-1 () ())
(defmethod run :around ((m mixin-1))
(incf level)
(format t "~%>~v@tmixin-1" (* 4 level))
(call-next-method)
(format t "~%<~v@tmixin-1" (* 4 level))
(decf level))
(defclass mixin-2 () ())
(defmethod run :around ((m mixin-2))
(incf level)
(format t "~%>~v@tmixin-2" (* 4 level))
(call-next-method)
(format t "~%<~v@tmixin-2" (* 4 level))
(decf level))
(defclass mixin-3 () ())
(defmethod run :around ((m mixin-3))
(incf level)
(format t "~%>~v@tmixin-3" (* 4 level))
(call-next-method)
(format t "~%<~v@tmixin-3" (* 4 level))
(decf level))
(defclass main (setup-mixin mixin-1 mixin-2 mixin-3) ())
(defmethod run ((m main))
(format t "~%-~v@tmain" (* 4 (1+ level))))
@wsgac
Copy link
Author

wsgac commented Oct 21, 2025

This is a short demonstration of how you can wrap your main method functionality with a series of mixins defining their own :around methods. Since the mixin methods are independent of each other, their order in the main superclass list can be altered, in effect modifying the order of execution.

When main is defined as follows:

(defclass main (setup-mixin mixin-1 mixin-2 mixin-3) ())

we get the following behavior:

CL-USER> (run (make-instance 'main))

>    mixin-1
>        mixin-2
>            mixin-3
-                main
<            mixin-3
<        mixin-2
<    mixin-1

If we rearrange the mixins in main's superclass list:

(defclass main (setup-mixin mixin-3 mixin-2 mixin-1) ())

we get a different order of execution:

CL-USER> (run (make-instance 'main))

>    mixin-3
>        mixin-2
>            mixin-1
-                main
<            mixin-1
<        mixin-2
<    mixin-3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment