dovt85093 2015-09-21 07:41
浏览 51
已采纳

几乎重复我自己

Combinitorial Explosion You have lots of code that does almost the same thing.. but with tiny variations in data or behavior. This can be difficult to refactor-- perhaps using generics or an interpreter? - Jeff Atwood via Coding Horror

In this case it is not lots of code, but it is still bugging me. I have a shared problem, that is when trying to connect to an IP, if it fails, I should retry with the next IP.

I have one function which generates a producer for NSQ:

//Since we are in a critical system, we try with each IP until we get a producer
var err error
for i, success := 0, false; i < len(ips) && !success; i++ {
    publisher, err = nsq.NewProducer(ips[i], nsq.NewConfig())
    if err == nil {
        success = true
    }
}

The other function that almost shares the same code is one which takes a NSQ consumer and connects it:

var err error
for i, success := 0, false; i < len(ips) && !success; i++ {
    err = consumer.ConnectToNSQD(ips[i])
    if err == nil {
        success = true
    }
}

I would like to get rid of this almost repeated code without sacrificing legibility. Ideas?

  • 写回答

2条回答 默认 最新

  • douna1895 2015-09-21 12:43
    关注

    You have it backwards. Your solution should follow the shape of the problem, not the shape of a particular solution. There's nothing in the solution that's worth refactoring. It's just going to add pointless complexity.

    For example,

    package main
    
    import "github.com/nsqio/go-nsq"
    
    // NewProducer is nsq.NewProducer with retries of an address list.
    func NewProducer(addrs []string, config *nsq.Config) (producer *nsq.Producer, err error) {
        if len(addrs) == 0 {
            addrs = append(addrs, "")
        }
        for _, addr := range addrs {
            producer, err = nsq.NewProducer(addr, config)
            if err == nil {
                break
            }
        }
        return producer, err
    }
    
    // ConnectToNSQD is nsq.ConnectToNSQD with retries of an address list.
    func ConnectToNSQD(c *nsq.Consumer, addrs []string) (err error) {
        if len(addrs) == 0 {
            addrs = append(addrs, "")
        }
        for _, addr := range addrs {
            err = c.ConnectToNSQD(addr)
            if err == nil {
                break
            }
        }
        return err
    }
    
    func main() {}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看