Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

idioms

go

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 ?

like image 522
nitimalh Avatar asked Jan 29 '23 21:01

nitimalh


1 Answers

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
like image 117
jdizzle Avatar answered Feb 02 '23 08:02

jdizzle