Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I’ve found it hard to apply this pattern in Go since, if Username is embedded in a struct, and you forget to set it, you’ll get Username’s zero value, which may violate your constraints.


But if you then create a constructor / factory method for that struct, not setting it would trigger an error. But this is one of the problem with Go and other languages that have nil or no "you have to set this" built into their type system: it relies on people's self-discipline, checked by the author, reviewer, and unit test, and ensuring there's not a problem like you describe takes up a lot of diligence.


It only relies on unit tests. The people can fail all day long and the unit tests will catch it every single time. Not special unit tests that attempt to seek out such issues, the same unit tests you are writing in languages that have a stricter type system.

If you forget to initialize a field and the tests don't notice, you didn't need the field in the first place, so it won't matter if it is left in an invalid state.

You just don't get the squiggly lines in your text editor. That's the tradeoff.


The pattern sounds nice in theory, but very cumbersome since now you have to obsessively ensure you have NewX calls everywhere or some form of "validated bool". In the end, you're just validating in a roundabout way and calling it "parsing".

I personally find being robust to errors and having clear error messages is the best option.

Don't focus so hard on getting things right, but rather dealing with things when they go wrong.


Why? You can easily call NewUsername inside NewAccount for example, just return the error. Or did I misunderstood?


Because go doesn’t have exhaustiveness checking when initialising structs. Instead it encourages “make the zero value meaningful” which is not always possible nor desirable. I usually use a linter to catch this kind of problem https://github.com/GaijinEntertainment/go-exhaustruct


I like this but in the examples would volume be calculated by width/length rather than being set?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: