duanci3845 2016-07-19 22:19
浏览 135
已采纳

减少Golang中的代码重复

I'm having trouble find the "go-way" to solve a code duplication issue. Here's the problem. Consider the following:

type (
  WithKey interface {
    key() string
  }

  SharedFunctionality interface {
    WithKey
    MethodA() string
    MethodB() string
    // ... etc ...
  }

  FirstType struct { ... }
  SecondType struct { ... }
  // ... etc ...
)
func (ft *FirstType) key() string { ... }
func (st *SecondType) key() string { ... }

Now, the methods in SharedFunctionality they only depend on the results of the key() method. I could implement them like the following:

func runMethodA(k WithKey) string {
  key := k.key()
  // do something and return a string
}
func runMethodB(k WithKey) string {
  key := k.key()
  // do something else and return a string
}

func (ft *FirstType) MethodA() string { return runMethodA(ft) }
func (ft *FirstType) MethodB() string { return runMethodB(ft) }
func (st *SecondType) MethodA() string { return runMethodA(st) }
func (st *SecondType) MethodB() string { return runMethodB(st) }

What I dislike about this approach is that, as I add more types (ThirdType, FourthType, etc) or as I add more methods to SharedFunctionality, I have to add tons of boilerplate code... specifically, for M methods in SharedFunctionality, and N types, I would have to spell out M*N one-liners like the 4 above.

What I would love to do is something like:

func (k WithKey) MethodA() string {
  key := k.key()
  // do something
}

In other words: I'd love to define a method on an Interface type. Meaning: all objects that implement "WithKey" would automatically get MethodA() string, MethodB() string, etc, therefore they would automatically implement the SharedFunctionality interface. Something like default methods in Java interfaces.

However, I know it's impossible to define a method in an Interface type...

What's the go-way of solving this problem?

I've seen an approach where I would create a struct with an anonymous field of the interface type, and then implement the methods there:

type SharedFuncStruct struct {
  WithKey
}
func (sfs *SharedFuncStruct) MethodA() string {
  key := sfs.key()
  // whatever
}
// same for MethodB()

Then to use it, I would do something like:

first := ... getFirstTypeValue()
sfs := &SharedFuncStruct{first}
sfs.MethodA() // etc

This looks like it could work, but it still feels like too much boilerplate code.

Any other alternatives?

  • 写回答

2条回答 默认 最新

  • doumindang2416 2016-07-21 16:32
    关注

    Fun fact: you can embed interfaces into structs, and the struct then automatically fulfills that interface. You can use this to effectively define methods on interfaces:

    https://play.golang.org/p/ZufTOzr9ig

    type (
        WithKey interface {
            key() string
        }
    
        SharedFunctionality interface {
            WithKey
            MethodA() string
            MethodB() string
        }
    
        KeyHolder struct {
            WithKey
        }
    
        FirstType struct { ... }
        SecondType struct { ... }
    )
    
    func (k *KeyHolder) MethodA() string {
        key := k.key()
        // ...
    }
    
    func (k *KeyHolder) MethodB() string {
        key := k.key()
        // ...
    }
    
    func NewSharedFunctionality(w WithKey) SharedFunctionality {
        return &KeyHolder{w}
    }
    
    func (ft *FirstType) key() string { ... }
    func (st *SecondType) key() string { ... }
    

    In this case, the KeyHolder struct embeds the WithKey interface, and thus can hold anything that has the key() string method (which both FirstType and SecondType have). You can then define MethodA and MethodB on that struct, and that struct will then fulfill both the WithKey interface (because it embeds it) and the SharedFunctionality interface, using whatever key is returned by the embedded WithKey.

    In other words, instead of wrapping FirstType in WithKey and then in SharedFunctionality (meaning FirstType itself has to define key(), MethodA(), and MethodB()), you wrap FirstType in WithKey, then embed it (as a WithKey interface) in some other structure that exists solely to define those default methods MethodA and MethodB, which then fulfills the SharedFunctionality interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?