DEV Community

Robin
Robin

Posted on

1 3

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay