Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a "constructor" function return an error or a null value?

Tags:

go

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
}
like image 813
We Stan Test Coverage Avatar asked Jan 13 '16 18:01

We Stan Test Coverage


People also ask

Can a constructor return null?

Java Constructors Never Return Null.

Why does the constructor not return any value?

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.

How do you handle a constructor error in C++?

[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.

Can constructor return a value in C++?

A return statement in the body of a constructor cannot have a return value.


1 Answers

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

like image 180
Bayta Darell Avatar answered Oct 15 '22 06:10

Bayta Darell