Pergunta

Are there languages that idiomatically use both notions at the same time? When will that be necessary if ever? What are the pros and cons of each approach?

Background to the question:

I am a novice (with some python knowledge) trying to build a better picture of how multimethods and interfaces are meant to be used (in general).

I assume that they are not meant to be mixed: Either one declares available logic in terms of interfaces (and implements it as methods of the class) or one does it in terms of multimethods. Is this correct?

Does it make sense to speak of a spectrum of OOP notions where:

  • one starts with naive subclassing (data and logic(methods) and logic implementation(methods) are tightly coupled)
  • then passes through interfaces (logic is in the interface, data and logic implementation is in the class)
  • and ends at multimethods (logic is in the signature of the multimethod, logic implementation is scattered, data is in the class(which is only a datastructure with nice handles))?
Foi útil?

Solução

This answer, to begin, largely derives from my primary experience developing in common-lisp and clojure.

Yes, multimethods do carry some penalty in cost, but offer almost unlimited flexibility in the ability to craft a dispatch mechanism that precisely models whatever you might look to accomplish by their specialization.

Protocols and Interfaces, on one hand, are also involved with sone of these same matters of specializations and dispatch, but they work and are used in a very different manner. These are facilities that follow a convention wherein single dispatch provides only a straightforward mapping of one specialized implementation for a given class. The power of protocols and interfaces is in their typical use to define some group of abstract capabilities that, when taken together, fully specify the API for thus concept. For example, a "pointer" interface might contain the 3 or 4 concepts that represent the notion of what a pointer is. So the general interface of a pointer might look like REFERENCE, DEREFERENCE, ALLOCATE, and DISPOSE. Thus the power of an interface comes from its composition of a group of related definitions that, together, express a compete abstraction -- when implementing an interface in a specific situation, it is normally an all-or-nothing endeavor. Either all four of those functions are present, or whatever this thing us does not represent our definition of pointer.

Hope this helped a little. Dan Lentz

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top