英文:
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) == 0
或color == ""
。
英文:
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 == ""
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论