Implementing an (aspect) Protocol for modules implementing another Protocol

On several occasions I’ve had this need to implement a Protocol for all modules implementing one other particular Protocol e.g.

defimpl Viewable, for: Doable do

One could argue to merge the two protocols into one, but in those few particular cases it is not applicable over the separation of concerns, as the protocols themselves are defined in two completely separate parts of the application and their respective implementations are more like two different behavioral aspects than just the protocols (i.e. they are not just wrapping the function calls to the structure modules but providing some additional behavior as well).

Any thoughts?

You can sort of achieve this by having the Viewable protocol fallback_to_any and then in the any clause check to see if the item provided implements Doable.

1 Like

True, but it’s not exactly the same thing as then you also need to raise if the protocol is not implemented i.e. you’re adding some boilerplate on case by case basis. Otherwise, this can also be implemented as a macro but that’s exactly my point here. The then/2 macro used to be implemented manually by different names and by different developers until it’s become an integral part of Elixir. My point here is why not add this one as well?