My application has the following model that I simplified on purpose, and I think there is a lot of code smell in the way I am using interfaces:
- Libraries have Collections
- Collections have Items
- Libraries know where the location if Item is.
Let's say I have ten libraries (that will be implemented in separated packages, each one with its specificities).
I want to manipulate the libraries in handlers to serve requests. So, I defined the following interfaces:
type Library interface {
ListCollections(prefix string) []Collection
GetItemLocation(item Item) string
}
type Collection interface {
SearchItems(query string) []Item
}
type Item interface {
Name() string
Summary() string
}
I cannot define an Item
struct as each one is different. However, with respect to the outer world, having the Item
interface is sufficient.
As you can see, I have methods returning interfaces and I don't really like it. Moreover, I struggle with, in this example, the GetItemLocation
part: it expects an Item, but I need to access fields of the Item (specific to each collection) so it forces me to type cast the argument inside the method.
Which patterns could I use to breakdown this complexity and write more diomatic go code?
Aucun commentaire:
Enregistrer un commentaire