DEV Community

Robin
Robin

Posted on

Lack of default constructor is hurting Go

How many times have you written a factory function just to initialize a struct with proper default value?

For example:

// PagingOption ...
type PagingOption struct {
    Page int
    Size int
}

We usually want BOTH to have default values. Let's say page=1&size=25, but anywhere we want to use PagingOption we are either

  1. Write and use a factory function which properly build a PagingOption
  2. Write and use an Init function which properly build a PagingOption
  3. Instantiate using object literal and fill it with default value
  4. Validate PagingOption in every consumer and fallback to default value if necessary

  • Option 1 forces all developer to remember not to use new(PagingOption) or PagingOption{}.
  • Option 2 forces all developer to remember calling .Init after initializing PagingOption
  • Options 3 forces all developer to know what is the agreed default values.
  • Options 4 forces all developer to remember checking default value before using the PagingOption

All options contribute to human error which can be mitigated just by having a proper constructor.

Top comments (1)

Collapse
 
atreya profile image
Atreya

You can always use the functional options pattern to assign default values...
dave.cheney.net/2014/10/17/functio...