News for hackers. Stuff that matters.
Re:Use Your Type System by lock1 on Thursday July 24, 2025 @01:49PM (#44673770)
I find regular OOP language constructor are too restrictive. You can't return something like Result<CorrectObject,ConstructorError> to handle the error gracefully or return a specific subtype; you need a static factory method to do something more than guaranteed successful construction w/o exception.

Does this count as a missing language feature by requiring a "factory pattern" to achieve that?

Re:Use Your Type System by 0x457 on Thursday July 24, 2025 @04:09PM (#44675425)
This is why constructors are dumb IMO and rust way is the right way.

Nothing stops you from returning Result<CorrectObject,ConstructorError> in CorrectObject::new(..) function because it's just a regular function struct field visibility takes are if you not being able to construct incorrect CorrectObject.

Re:Use Your Type System by henry700 on Thursday July 24, 2025 @02:20PM (#44674179)
The natural solution for this is a private constructor with public static factory methods, so that the user can only obtain an instance (or the error result) by calling the factory methods. Constructors need to be constrained to return an instance of the class, otherwise they would just be normal methods.

Convention in OOP languages is (un?)fortunately to just throw an exception though.

Re:Use Your Type System by Conscat on Thursday July 24, 2025 @05:21PM (#44676343)
In languages with generic types such as C++, you generally need free factory functions rather than static member functions so that type deduction can work.
Re:Use Your Type System by Jensson on Thursday July 24, 2025 @09:39PM (#44678507)
> You can't return something like Result<CorrectObject,ConstructorError> to handle the error gracefully

Throwing an error is doing exactly that though, its exactly the same thing in theory.

What you are asking for is just more syntactic sugar around error handling, otherwise all of that already exists in most languages. If you are talking about performance that can easily be optimized at compile time for those short throw catch syntactic sugar blocks.

Java even forces you to handle those errors in code, so don't say that these are silent there is no reason they need to be.