Simplifieng error checking

I was wondering if this validation can be simplified more.

func (f *foo) Validate() (err error) {
  if err = conform.Strings(f); err != nil {
    return
  }

  _, err = govalidator.ValidateStruct(f)
  return
}

I will appreciate any advice/suggestion.

Thanks

I’d advice against the named return variable, otherwise it looks simple enough as is to me.

2 Likes

Will you ever return an error?

Is this you meant?

func (f *foo) Validate() error {
  if err := conform.Strings(f); err != nil {
    return err
  }

  _, err := govalidator.ValidateStruct(f)
  return err
}
2 Likes

yes

I’d keep the good case on the first code level:

func (f *foo) Validate() error {
    if err := conform.Strings(f); err != nil {
        return err
    }

    if _, err := govalidator.ValidateStruct(f); err != nil {
        return err
    }

    return nil
}
1 Like

I’d stop on this, it seems pretty good. It’s enough short and clear.

1 Like

Ideally you also want to decorate your errors: fmt.Errorf("value does not conform: %v", err) and fmt.Errorf("validation failed: %v", err). Use something like github.com/pkg/errors to retain the original error.

1 Like