Reputation: 961
Is there anything wrong with an interface with more that one function assigned to it ?
Everywhere I read, an interface should ideally have only one method (which is what the interface should be named after). But are there any pit falls to having more than one method for an interface ? Ex.
type FooMgrInterface interface {
CreateFoo(hostname string, fooConfig interface{}) (uuid string, err error)
DeleteFoo(hostname string, fooID string) (err error)
CreateBar(hostname string, barID string, barConfig interface{}) (uuid string, err error)
DeleteBar(hostname string, barID string) (err error)
AttachBar(hostname string, fooID string, bars []string) (err error)
DetachBar(hostname string, barID string) (err error)
GetBars(hostname string) (bars []Bar, err error)
GetBar(hostname string, barID string) (bar Bar, err error)
GetFoo(hostname string, fooID string) (foo Foo, err error)
GetFoos(hostname string) (foos []Foo, err error)
}
If so how could the above interface be simplified or (maybe) split into multiple interfaces ?
Upvotes: 4
Views: 1842
Reputation: 3547
Look for inspiration in https://golang.org/src/io/io.go
You will see:
a. "Atomic" interfaces: Reader
, Writer
, Closer
, Seeker
b. Composed interfaces: ReaderWriter
, ReaderWriterSeeker
, ReaderSeekerCloser
etc.
Golang will not complaint about gigantic interfaces, it's you and your collegues will have complaints about big monolithic interfaces.
I recomend divide your interface to 4 (maybe 2) interfaces: FooOps
, FoosOps
, BarOps
, BarsOps
and then define composed interfaces from them.
Upvotes: 3
Reputation: 4154
There's nothing wrong with it, in that the language supports it just fine.
I believe the authors are offering architectural advice based on experience. Specifically, if your interface has many methods, you likely have the wrong abstraction somewhere.
You can ask yourself some clarifying questions:
NewFoo(owner FooMgrInterface) *Foo
Upvotes: 6