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