internal/service: GetCoupons method improvements
zalgonoise opened this issue · 0 comments
zalgonoise commented
- If the method is set to support multiple codes at a time, it may be best to declare it as a variatic function. This would allow it to accept any amount of codes (one-to-many) without actually having to write two functions, or adapting to either implementation:
GetCoupons(codes ...string) ([]Coupon, error)
- Error
e
is initialized with anil
value. This is not necessary as it's its default value already asvar e error
- Errored calls to
FindByCode
will lose its underlying error value:- the raised error is not being included in the
fmt.Errorf
call to definee
when it isnil
. It should always be present - when
e
is not nil and a new error is appended to it, it's shadowing the previous error. While the error string will expand for each error, only one (locally declared) error is returned.
- the raised error is not being included in the
- To mitigate the situation above one could:
- A) update to Go 1.20 and leverage
errors.Join
; by initializing a list of errors, appending non-nil errors to it, and if longer than zero, returning the list asreturn nil, errors.Join(e...)
- B) if Go 1.18 is required, implement
errors.Join
locally, as it's simple and affordable (seezalgonoise/x/errors
) - C) short-circuit out on the first error, returning it
- A) update to Go 1.20 and leverage
- Checking for the error is still very important, and should be done before the last return (returning
nil, e
instead ofcoupons, e
)