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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么