beatgammit
unread,Sep 11, 2012, 9:21:35 PM9/11/12Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golan...@googlegroups.com
I am working on a module system, so I've defined an interface for common functionality, like so:
type Module interface {
Id() string
Format(io.Reader) io.Reader
Settings() map[string]string
Set(string, string)
}
There are a bunch more methods defined, but this should serve for the example. For example, these modules fit into some kind of data formatter. Each module formats data differently, but they each have an id, settings (and a way to set them), and a format function that takes an io.Reader and returns a Reader which does a kind of translation in between (for example encryption, annotation, etc).
Each module will have a different Format() and Id(), but the settings may just be duplication of code. For example, most of the modules store/retrieve their settings in a database, but some just store them in memory and have to be set each time. For the majority of these modules, I have redundant code that can easily be abstracted out, but the functions must be there for the few that don't work that way.
My actual implementation has a lot of functions, many of which can be abstracted away.
In languages with polymorphic classes, I could override an inherited method, or leave it as is. However, I couldn't find an easy way of doing this in Go without duplicating code or making a nasty hack.
What I've done so far is created another type, Shell, that implements all of the functions, but still allows for some flexibility:
type Shell struct {
ModFormat(io.Reader) io.Reader
ModSettings() map[string]string
ModSet(string, string)
}
If Mod* != nil, then it calls it, otherwise it does it's default handling. Values that don't change (like Id()) are just set once in the constructor of Shell (can't be overridden).
Is there a better way of doing this? This doesn't seem very idiomatic, especially with the Mod* functions... Have any of you run into a similar problem? I've thought about how to re-architect it to avoid the problem, but I haven't been able to come up with anything that doesn't require a lot of code duplication or global functions.
Thanks!