猿问

几乎重复我自己

组合爆炸你有很多代码几乎都在做同样的事情……但在数据或行为上有微小的变化。这可能很难重构——也许使用泛型或解释器?- 杰夫阿特伍德通过编码恐怖


在这种情况下,它不是很多代码,但它仍然困扰着我。我有一个共同的问题,即尝试连接到 IP 时,如果失败,我应该使用下一个 IP 重试。


我有一个函数可以为 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

    }

}

另一个几乎共享相同代码的函数是一个接受 NSQ 消费者并连接它的函数:


var err error

for i, success := 0, false; i < len(ips) && !success; i++ {

    err = consumer.ConnectToNSQD(ips[i])

    if err == nil {

        success = true

    }

}

我想在不牺牲易读性的情况下摆脱这个几乎重复的代码。想法?


慕少森
浏览 145回答 2
2回答

aluckdog

你把它倒过来了。您的解决方案应该遵循问题的形状,而不是特定解决方案的形状。解决方案中没有任何内容值得重构。它只会增加毫无意义的复杂性。例如,package mainimport "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) {&nbsp; &nbsp; if len(addrs) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; addrs = append(addrs, "")&nbsp; &nbsp; }&nbsp; &nbsp; for _, addr := range addrs {&nbsp; &nbsp; &nbsp; &nbsp; producer, err = nsq.NewProducer(addr, config)&nbsp; &nbsp; &nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return producer, err}// ConnectToNSQD is nsq.ConnectToNSQD with retries of an address list.func ConnectToNSQD(c *nsq.Consumer, addrs []string) (err error) {&nbsp; &nbsp; if len(addrs) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; addrs = append(addrs, "")&nbsp; &nbsp; }&nbsp; &nbsp; for _, addr := range addrs {&nbsp; &nbsp; &nbsp; &nbsp; err = c.ConnectToNSQD(addr)&nbsp; &nbsp; &nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return err}func main() {}

大话西游666

也许像这样?var publisher *nsq.ProducerconnectToWorkingIP(ips, func(ip string) error {&nbsp; &nbsp; var err error&nbsp; &nbsp; publisher, err = nsq.NewProducer(ip, nsq.NewConfig())&nbsp; &nbsp; return err})connectToWorkingIP(ips, func(ip string) error {&nbsp; &nbsp; return consumer.ConnectToNSQD(ip)})func connectToWorkingIP(ips []string, f func(string) error) {&nbsp; &nbsp; for i, success := 0, false; i < len(ips) && !success; i++ {&nbsp; &nbsp; &nbsp; &nbsp; err := f(ips[i])&nbsp; &nbsp; &nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success = true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答