4 ms·
Is it possible to implement the same protocol for a particular type in multiple ways?
by pdhborges 15y ago
Is it possible to implement the same protocol for a particular type in multiple ways?
- puredanger 15y agoNo, as a reimplementation will effectively replace the prior implementation. But I think you should ask whether that question makes sense. If you're dispatching based on something other than just type (some information that would allow you to choose one of multiple implementations) than you should probably either a) put that logic inside the protocol implementation for that type or b) use multimethods which let you use an arbitrary dispatch function that can take both type and other information into account. If you choose a), you could actually layer another protocol or other dispatch mechanism under the initial call if you need to.
- pdhborges 15y agoImagine I have a JSONfiable protocol and I have a generic function to traverse a structure that uses the protocol to make a JSON document. It would be nice if the caller had a way to change the format.
- puredanger 15y agoYou can change the implementation of the protocol, but then it's changed (in that it replaces the prior version). When you see something of type X, the protocol says what to do when you encounter a function on X. If you want more than one kind of thing to happen, then you shouldn't use a protocol. For instance, it would be perfectly feasible to use a multimethod that dispatches on both type and output format. Or a protocol that dispatches on type, then dispatches a different function on format.