Should a “constructor” function return an error or

2020-08-14 07:36发布

Given the a constructor function such as

func NewSomething(name, color string) *Something {
    s := Something{name, color}
    return &s
}

Should this function include sanity checks, such as &name == nil, or len(name) == 0? If this function should contain sanity checks, what value should be returned from the constructor? A nil value, or an error (errors.New(...))? An example is included below.

func NewSomething(name, color string) *Something {
    if &name == nil || len(name) == 0 {
        return nil
    }

    if &color== nil || len(color) == 0 {
        return nil
    }

    s := Something{name, color}
    return &s
}

标签: go
1条回答
欢心
2楼-- · 2020-08-14 08:04

Return an error. It is not idiomatic to use a distinguished value (such as nil) to indicate an error.

func NewSomething(name, color string) (*Something, error) {
  if name == "" {
    return nil, errors.New("bad name")
  }

  if color == "" {
    return nil, errors.New("bad color")
  }

  s := Something{name, color}
  return &s, nil
}

Aside: The expression &anyVariable == nil always evaluates to false. Simplify the checks to len(color) == 0 or color == "".

查看更多
登录 后发表回答