zalgonoise/eljoth-go-code-review

internal/service: GetCoupons method improvements

zalgonoise opened this issue · 0 comments

  • 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 a nil value. This is not necessary as it's its default value already as var 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 define e when it is nil. 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.
  • 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 as return nil, errors.Join(e...)
    • B) if Go 1.18 is required, implement errors.Join locally, as it's simple and affordable (see zalgonoise/x/errors)
    • C) short-circuit out on the first error, returning it
  • Checking for the error is still very important, and should be done before the last return (returning nil, e instead of coupons, e)