The Common Lisp Object System (CLOS) supports multiple dispatch (multimethods). When is this a useful feature in practice? I’m not just looking for an example of hypothetical functionality that would be easier to implement with multiple dispatch[1]. I’m looking for examples of where it’s useful in real software, for any value of real that means it would get written for something other than just an example.
[1] In programming tutorials, are examples contrived more often than not?
- Anytime you use the visitor pattern.
- Anytime you have a binary operator that needs to dispatch on both params (eg. bullet hits rock vs bullet hits spaceship vs spaceship hits rock)
- Anytime you want specialization based on the parameter (eg. C++’s vector<bool> specialization, component systems where the component may or may not exist)
An easy to understand example would be arithmetic, where you might have definitions
for
(plus integer integer)
(plus float integer)
(plus integer float)
and so on.
Used carefully, this can be a wonderful mechanism. Used carelessly..well, you get
what you deserve.
1
You can use them for generalized setters.
Instead of writing
(defmethod set-[specific-property] ((obj obj-type)) ())
for each [specific-property] setter that you want, you can use a single generic function to dispatch:
(defmethod set- ((prop (eql :foreground)) (obj window)) ())
(defmethod set- ((prop (eql :background)) (obj t)) ())
etc…