douchen5971 2015-10-20 14:49
浏览 6

最小化Golang中的接口

In golang, interfaces are extremely important for decoupling and composing code, and thus, an advanced go program might easily define 1000s of interfaces .

How do we evolve these interfaces over time, to ensure that they remain minimal?

  • Are there commonly used go tools which check for unused functions ?

  • Are there best practices for annotating go functions with something similar to java's @Override, which ensures that a declared function is properly implementing a expected contract?

Typically in the java language, it is easy to keep code tightly bound to an interface specification because the advanced tooling allows us to find and remove functions which aren't referenced at all (usually this is highlighted automatically for you in any common IDE).

  • 写回答

2条回答 默认 最新

  • dongzha5934 2015-10-20 14:56
    关注

    Are there commonly used go tools which check for unused functions ?

    Sort of, but it is really hard to be sure for exported interfaces. oracle can be used to find references to types or methods, but only if you have all of the code that references you availible on your gopath.

    can you ensure a type implements a contract?

    If you attempt to use a type as an interface, the compiler will complain if it does not have all of the methods. I generally do this by exporting interfaces but not implementations, and making a constructor:

    type MyInterface interface{
        Foo()
    }
    type impl struct{}
    func (i *impl) Foo(){}
    func NewImpl() MyInterface{
        return &impl{}
    }
    

    This will not compile if impl does not implement all of the required functions.

    In go, it is not needed to declare that you implement an interface. This allows you to implement an interface without even referencing the package it is defined in. This is pretty much exactly the opposite of "tightly binding to an interface specification", but it does allow for some interesting usage patterns.

    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条