4 ms·
This is not elegant. It also has overhead. Stick with the simple `const Red Color = "red"`, you're not gaining a lot by doing all these strange type contortion
by SPBS 3y ago
This is not elegant. It also has overhead. Stick with the simple `const Red Color = "red"`, you're not gaining a lot by doing all these strange type contortions in Go. Seriously consider what you are protecting against, and whether it's an imagined bogeyman.
"Oh but someone may try to cast arbitrary values to my package type" Okay but who is that going to hurt? You or them? Will they get hit with errors early on in the development lifecycle if they do something silly like this? Are you actually going through all these lengths for nothing?
- ollien 3y agoWhat overhead is there at runtime?
- the_gipsy 3y agoIt's stuff that just creeps in. Enum values can come from outside (json, anything non-literal). Now you have to do validation, because the bad values parse and for sure exist at some stage in your program. It's not a bogeyman.
- Groxx 3y agoAccidental zero value enums are a constant plague as far as I've seen. Almost any defense is worth it.
- arp242 3y agoYeah, this is the big thing. Honestly I'm not so worried about people using pkg.fun("red") or pkg.fun(25) instead of pkg.fun(pkg.Red) if they really want to, and in some cases it's IMHO even fine (e.g. HTTP status codes, where everyone knows what 404, 500, etc. mean). It's pkg.fun(someVar) where someVar is accidentally 0 or "" because it comes from 3 functions away.
- the_gipsy 3y agozero-values are the root of all go problems. Lack of sum/union/algebraic types are the root if zero-values.
- SPBS 3y agoYes it is important to have validation for anything coming in from outside (json, the database, etc). This is done by creating a map with the valid enum values and checking at runtime. This compile time solution wouldn't have worked for validating enums sent in json anyway, it's purely a defense mechanism against library users trying to cast arbitrary values to a package type.