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条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格