nitimalh
nitimalh

Reputation: 961

Go Interfaces with more than one method - Acceptable or unacceptable?

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

Answers (2)

Alex Yu
Alex Yu

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

jdizzle
jdizzle

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:

  • How many different implementations of this interface will there be?
  • How many of them will have identical method implementations?
  • How are the Foos/Bars attached to the implementor? Would it be simpler to reverse it somehow? eg something like NewFoo(owner FooMgrInterface) *Foo

Upvotes: 6

Related Questions