common-lispclos

DEFGENERIC + DEFMETHOD vs. DEFUN for implementation?


I have file R and two files A, B.

R is always loaded.

A xor B are loaded depending on platform features. I have a function which should exist no matter the platform, call it F.

What are the advantages/disadvantages of using:

  1. DEFGENERIC on F in R, then DEFMETHOD on F in both A, B
  2. DEFUN on F in both A, B'

On the face of it, they should be the same. Is it more than a matter of preference?

EDIT: The implementations of F in A vs. B are different.

I am currently employing the first method as it makes it clear that the function is generic and has implementations, but am curious on why it would matter that much compared to the second method.


Solution

  • In my opinion the advantages or disadvantages of using either defgeneric or defun in your case are not different from the general case, meaning that there is no additional constraint here compared to the usual choice between generic functions and regular ones.

    Generally speaking, functions are simpler and possibly more efficient to use based on the fact that they have less requirements (no dispatch, no method combination, etc.) thought in practice there are a lot of optimizations that exist to make the distinction less important.

    Generic functions can help you if you have a platform A' which is almost like A but with some adjustments, in which case you could specialize some methods.

    In your question you consider two options, but note that you are not limited to that. See for example how Slime defines two macros, definterface and defimplementation, to register a set of necessary backend functions and their implementations on various platforms.

    You can also look at the various libraries called by convention trivial-*stuff* which merge together various implementation-specific code for doing *stuff* under a unified interface (see CLiki/Trivial for a list of such libraries).