Hacker News new | ask | show | jobs
by DemocracyFTW2 41 days ago
> Constructors Shouldn't Throw

wrong

1 comments

this is not helpful, please explain why you think this

If we interpret "constructor" more generically as setup, one of my preferred languages, Go, does not have constructors, but we do have similar setup functions, which typically return errors, and we handle them as soon as possible without breaking out from the designed control flow.

I think elsewhere in this thread the point has already been made so I thought to spare the Ink. A constructor is essentially a function that returns a value. There's little reason to think that constructors are more than that. A few examples: in JS, a constructor is a method called `constructor()`. It's a bit special in that it's the method that is privileged to be the one called when the class name is preceded by the keyword `new`, but that's almost about it. It can be replaced or supported by one or more factory functions, and this is what happened with NodeJS's `Buffer` class and generals JS's `Array` class. In Ruby, the constructor is just a method called `new()`, and I guess it's not special beyond there being a convention to construct new instances with a method called `.new()`. Like any function, a constructor has an input and an output value. For example, in `new Point 3, 4` the input is the pair of numbers `( 3, 4 )` (here written spread out, but it doesn't matter), and its output is an instance of class `Point`. Say you have a class List that accepts as only parameter the length (number of elements) of the `List`. When I call a function `build_list length: -4` I expect the `length` argument to be suitably interpreted, or an error to be thrown. Most of the time a list with a negative number of elements does not make a lot of sense, so the natural thing is to indicate an error, which in many current languages is done by throwing an exception so as to prevent silent failures. When I call a constructor as `new List length: -4` I naturally expect the exact same considerations to apply.
In go there are the "init" functions, but those do not return a possible error result.

I guess you're thinking more of package constructor methods, such as NewFoo, which tend to return the new object and an error value.

yes, I use init sparingly and generally panic, for low level program startup, versus the NewFoo functions, which are for dynamic objects the way constructors are used, I use NewFoo -> (Foo, error) for internal runtime, client, and configuration handling as well