Simplifying Go Code -
i have 2 functions shown below similar, using different functions query db. since go doesn't encourage overloaading methods, redundancy acceptable? or should refactor them 1 function? comments welcomed.
var getcustomers = func() ([]customer, error) { return nil, nil } var getcustomerbyid = func(int64) (*customer, error) { return nil, nil } func listcustomer(w http.responsewriter, r *http.request) *apperror { cus, err := getcustomers() if err != nil { return &apperror{err, "no customer found", 404} } res, err := json.marshal(cus) if err != nil { return &apperror{err, "can't display record", 500} } fmt.fprint(w, string(res)) return nil } func viewcustomer(w http.responsewriter, r *http.request, id int64) *apperror { cus, err := getcustomerbyid(id) if err != nil { return &apperror{err, "no customer found", 404} } res, err := json.marshal(cus) if err != nil { return &apperror{err, "can't display record", 500} } fmt.fprint(w, string(res)) return nil }
suggestion use -1 list customer, i'm not sure if best can be:
func viewcustomer(w http.responsewriter, r *http.request, id int64) *apperror { var c *customer var clist []customer var err error if id < 0 { clist, err = getcustomers() res, err := json.marshal(clist) if err != nil { return &apperror{err, "can't display record", 500} } fmt.fprint(w, string(res)) return nil } else { c, err = getcustomerbyid(id) res, err := json.marshal(c) if err != nil { return &apperror{err, "can't display record", 500} } fmt.fprint(w, string(res)) return nil } }
since go doesn't encourage overloaading methods, redundancy acceptable? or should refactor them 1 function?
the answer question depends heavily on real code , task. if listing 1 customer different listing several customers (that is, need different information , have different presentation logic), i'd duplication here not bad, since difference may grow larger in future, dry solution turn if
, switch
mess quickly. (i've had similar experience on non-go project , since think dry should not fanatic it.)
on other hand, if you're making, json api, make more dry. define getcustomers
function this:
func customers(ids ...int64) ([]customer, error) { /* ... */ }
this way can:
- call
customers()
, customers; - call
customers(42)
, customer id 42; - call
customers(someids...)
, multiple customers ids.
all can done in 1 handler in straightforward way.
all comments welcomed.
two nitpicks on code:
getter methods in go idiomatically named
foo
, notgetfoo
, usedcustomers
in example. calldb.customers(ids...)
, looks lot getter method.what's
var foo = func()
notation? unless there reason (like using these functions closures), i'd suggest stickingfunc foo()
notation, since it's more idiomatic , easiergrep
. edit: op pointed out in comments, casevar foo = func()
notation of course functions can faked in testing, shown in andrew gerrand's testing techniques talk.
i hope helps.
Comments
Post a Comment