“构造函数"应否函数返回错误或空值? [英] Should a "constructor" function return an error or a null value?
问题描述
给出一个构造函数,例如
Given the a constructor function such as
func NewSomething(name, color string) *Something {
s := Something{name, color}
return &s
}
此功能是否应包含健全性检查,例如& name == nil
或 len(name)== 0
?如果此函数应包含完整性检查,则构造函数应返回什么值? nil
值还是错误( errors.New(...)
)?下面包括一个示例.
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
}
推荐答案
返回错误
.使用可分辨的值(例如 nil
)来指示错误不是惯用的.
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
}
此外:表达式& anyVariable == nil
始终求值为 false
.将检查简化为 len(color)== 0
或 color =="
.
Aside: The expression &anyVariable == nil
always evaluates to false
. Simplify the checks to len(color) == 0
or color == ""
.
这篇关于“构造函数"应否函数返回错误或空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!