For a given type Data , I would like to define a set of filters, each processing Data in a certain way. Some filters only need the data to be processed, other may need additional parameters.
type Data struct {
...
}
I want to be able to define a list of filters, and apply them sequentially to an instance of Data. To acheive this, I defined a Filter interface :
type Filter interface {
Apply (d *Data) error
}
To define a filter, all I have to do is create a new type and define the Apply method for it.
Now, let’s say I have a filter that does not need any additional information. Is it good practice to define it as an empty struct ?
type MySimpleFilter struct {}
func (f *MySimpleFilter) Apply (d *Data) {
...
}
I’d argue this is good practice if you have no use for a Field, especially compared to using another type (i.e.
type MySimpleFilter int) because an empty struct uses no space:https://codereview.appspot.com/4634124
and it can still fulfill interface contracts (hence can be more useful than a functional approach in some cases).
This can also be a good idiom when using a map that you have no use for the value (i.e.
map[string]struct{}). See this discussion for details:https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/lb4xLHq7wug