“constructor”函数应该返回错误还是空值?

huangapple go评论84阅读模式
英文:

Should a "constructor" function return an error or a null value?

问题

给定一个构造函数,例如:

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

这个函数是否应该包含一些健全性检查,比如 &name == nil 或者 len(name) == 0?如果这个函数应该包含健全性检查,构造函数应该返回什么值?是 nil 值还是一个错误(errors.New(...))?下面是一个示例:

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
}

请注意,这只是一个示例,具体的健全性检查和返回值应根据实际需求进行调整。

英文:

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
}

答案1

得分: 21

返回一个错误。使用特殊值(如nil)来表示错误不是惯用的做法。

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
}

另外:表达式&anyVariable == nil始终评估为false。可以简化检查条件为len(color) == 0color == ""

英文:

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 == "".

huangapple
  • 本文由 发表于 2016年1月14日 02:43:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/34774615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定