Go Multiple Way Interfaces - Acceptable or Not Acceptable?

Is there something wrong with an interface with more than one function assigned to it?

Everywhere I read, ideally an interface should only have one method (which should be named with the name of the interface). But is there any pit that has more than one method for an interface? Example.

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 can you simplify or perhaps dividing this interface into multiple interfaces?

+3


source to share


2 answers


Look for inspiration at https://golang.org/src/io/io.go

You will see:

and. "Atomic" interfaces: Reader

, Writer

, Closer

,Seeker



b. Structured Interfaces: ReaderWriter

, ReaderWriterSeeker

, ReaderSeekerCloser

etc.

Golang won't complain about giant interfaces, you and your colleagues will complain about large monolithic interfaces.

I recommend the Interface 4 (possibly 2) interface: FooOps

, FoosOps

, BarOps

, BarsOps

, and then determine the one consisting interfaces.

+2


source


There is nothing wrong with that, because the language supports it just fine.

I believe the authors are offering architecture advice based on experience. In particular, if your interface has many methods, you probably have the wrong abstraction.



You can ask yourself a few clarifying questions:

  • How many different implementations of this interface will there be?
  • How many of them will have identical method implementations?
  • How are Foos / Bars tied to the developer? Would it be easier to undo it in some way? for example something likeNewFoo(owner FooMgrInterface) *Foo

+6


source







All Articles