go - Almost Repeating Myself -
combinitorial explosion have lots of code same thing.. tiny variations in data or behavior. can difficult refactor-- perhaps using generics or interpreter? - jeff atwood via coding horror
in case not lots of code, still bugging me. have shared problem, when trying connect ip, if fails, should retry next ip.
i have 1 function generates producer nsq:
//since in critical system, try each ip until producer var err error i, success := 0, false; < len(ips) && !success; i++ { publisher, err = nsq.newproducer(ips[i], nsq.newconfig()) if err == nil { success = true } }
the other function shares same code 1 takes nsq consumer , connects it:
var err error i, success := 0, false; < len(ips) && !success; i++ { err = consumer.connecttonsqd(ips[i]) if err == nil { success = true } }
i rid of repeated code without sacrificing legibility. ideas?
you have backwards. solution should follow shape of problem, not shape of particular solution. there's nothing in solution that's worth refactoring. it's going add pointless complexity.
for example,
package main import "github.com/nsqio/go-nsq" // newproducer nsq.newproducer retries of address list. func newproducer(addrs []string, config *nsq.config) (producer *nsq.producer, err error) { if len(addrs) == 0 { addrs = append(addrs, "") } _, addr := range addrs { producer, err = nsq.newproducer(addr, config) if err == nil { break } } return producer, err } // connecttonsqd nsq.connecttonsqd retries of address list. func connecttonsqd(c *nsq.consumer, addrs []string) (err error) { if len(addrs) == 0 { addrs = append(addrs, "") } _, addr := range addrs { err = c.connecttonsqd(addr) if err == nil { break } } return err } func main() {}
Comments
Post a Comment