Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Half Constructed Objects Are Unnecessary (jerf.org)
8 points by todsacerdoti 11 months ago | hide | past | favorite | 3 comments


I'm also bothered by half-constructed objects. In my previous job, I was on a team creating a Go project that integrated two different parts of the company. It was an HR company, with lots of random fields in objects.

The API given to us often returned objects with only certain values filled out. Go encourages this, because there it is so easy to do that. `StructName{}` will create a struct, and is easier than filling out values. It will fill out all the values with the "zero value" of the thing.

And there's no way to know if you have a zero value! I would commonly get back an object and have to dig into the code or ask people to find out when certain values would be filled out!

Compare to a language where you have to provide a constructor. Fewer people would write:

public ClassName() { var1 = 0; var2 = ""; }

It lead me to be able to trust values less than I had to in other languages I've used.


Yeah, if I could go back in time and tweak Go, removing the idea that zero values should generally be "valid" and that anyone the ability to name an exported type should be able to create a zero value of that type would be pretty high on my list of priorities. Not the highest, but it's up there.

I think it's one of those ideas that makes sense at first because it's easy to come up with examples of objects that can be constructed legally as zero values, and then convince yourself that maybe we live in a world where most values can be so constructed. The standard library has a number of them. However, I find the techniques for constructing them gas out long before the problem is solved. Unfortunately, it's the sort of thing that only really becomes proved once the language goes 1.0 already.

However, in pretty much any language, it's hard to avoid the user having some ability to fill out even "mandatory" fields in some invalid manner. You can impose terrifically strong typing on a value, but if the user wants to slap a "0" into the Price field "just to get the object constructed", there's not a lot you can do to stop them in the end. Or, if "0" is forced to be invalid, 0.01 or some other value. Programmers can be quite creative in pursuing bad ideas in their designs....


> However, in pretty much any language, it's hard to avoid the user having some ability to fill out even "mandatory" fields in some invalid manner.

I 100% agree. It's just that go seems to make it easier to make invalid values than valid ones, because the programmer doesn't have to actually type the values that end up invalid.




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

Search: