why do we need constructor function

tags: learning go programming

content

im seeing code like:

type User struct {
	ID int
	Name string
}
func NewUser(id int, name string) User {
	return User{
		ID: id,
		Name: name,
	}
}

what’s the point? why not just use:

user := User{...}

reason 1

  • we can have validation logic in the constructor function
func NewUser(id int, name string) (User, error) {
	if id <= 0  // ...
	if name == ""  // ...
}

reason 2

  • code decoupling
  • in the future, if there’s a new field in User struct, then we can use constructor function to
    • set default value (without this, Go doesn’t support default value!)
    • keep original code working
      • otherwise, if we use user:=User{id, name}, we have to update every single place where it’s used
type User struct {
	ID int
	Name string
	Email string  // new field!
}
func NewUser(id int, name string) User {
	return User{
		ID: id,
		Name: name,
		Email: "",
	}
}
func NewUserWithEmail(id int, name string, email string) User {
	return User{
		ID: id,
		Name: name,
		Email: email,
	}
}

Note

do notice that we still need a separate function NewUserWithEamil to accommodate the change

up

down

reference