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 asnil
) to indicate an error.Aside: The expression
&anyVariable == nil
always evaluates tofalse
. Simplify the checks tolen(color) == 0
orcolor == ""
.