I often face the problem of wanting to add additional methods to classes I don't control. For instance, I might want to have a function prettyPrint
that can operate on different object types that do not have a unified api (e.g. special __str__
methods).
The Nice
language and R
accomplishes this using multimethods, which avoid the Visitor Pattern nicely. For instance, R
has the plot()
function. Individual programmers can create new classes to define data types (e.g., network graphs or stock ticker data). A secondary user/programmer could then write a plot function to fill out the functionality, even though they don't have access to the graph or stock ticker code, or the code of other plot functions.
Given that I would like to add lots of functionality later, using class.method()
seems infeasible. Lots of class_plot()
functions for each type also seems like a bad idea. Defining one big plot()
function that checks types isn't extensible.
What are alternatives to multimethods? In particular, I'm interested in designs that might work in Jython and Scala.