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
}
Java Constructors Never Return Null.
No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.
[17.8] How can I handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.
A return statement in the body of a constructor cannot have a return value.
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 == ""
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With