Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it reasonable to use defmethod instead of defun even though there is no direct link between the class and the function/method

Consider this example:

There is a class named 'first', which is defined in package 'a'.

There is also a package 'b' which uses module 'a' functionalities. Certain functions of package 'b' would require a object of class 'first' as a parameter. But besides this, there is no direct logical link between package 'a' and 'b'.

Now I wonder if it would be reasonable to write (defmethod package-b-function ((param first)) #|do stuff..|#) instead of a normal function, as the function needs the object and defining a method would clarify this for both the runtime environment and other users of package 'b'.

I used to program in C++/Java therefore I am not familiar with the OOP conventions to be used in this case.

Appreciate your insight.

like image 234
Sim Avatar asked Aug 03 '12 13:08

Sim


2 Answers

Methods in Common Lisp don't quite work the same way as the languages you note (see the appropriate two chapters of Practical Common Lisp for details). In a nutshell, at a very high level, you need to think about OO in lisp as "methods specialize on classes" rather than "classes have methods".

That said, yes, I think it would be perfectly reasonable for a package to have a method specializing on a class that's defined elsewhere. Specifying the type of input you're expecting clarifies intent for future readers (and may or may not help in optimization, but that's not terribly important from my perspective). If you're defining an ASDF system for your package, make sure to import the appropriate symbol, and depends-on the appropriate package.

Just as a footnote, be aware that Common Lisp isn't particularly object oriented as a language (for example, you'll run into some odd corners if you decide that a particular class should have length, pop or push methods, or specialize on arithmetic operations).

like image 195
Inaimathi Avatar answered Sep 27 '22 20:09

Inaimathi


Common Lisp provides ordinary functions and generic functions.

As a first rule use this:

Use generic functions when you want to assemble the effective method from various available methods (for example when programming with Mixins) or when you want to select a method based on runtime arguments.

If you don't need this advanced behavior, then just use ordinary functions. Documenting what kind of arguments an ordinary function needs and corresponding runtime checks can be done with other CL functionality:

  • CHECK-TYPE
  • ASSERT
  • Documentation strings
  • DECLARE argument types
like image 24
Rainer Joswig Avatar answered Sep 27 '22 19:09

Rainer Joswig