4 ms·
How does this work for constructors? I have the habit of guarding against poor input. If a value is null, I'll throw a null pointer exception or an illegal argu
by virmundi 15y ago
How does this work for constructors? I have the habit of guarding against poor input. If a value is null, I'll throw a null pointer exception or an illegal argument exception. While I recognize that both of these unchecked exceptions, I could just as easily throw a ModelArgumentException that extends from Exception.
The reason I throw such exceptions is that I don't want my object to be constructed with invalid state (this is especially true when my object is immutable, but has actions). Since I cannot return an Either, I believe that I must either A) throw an exception or B) allow invalid state. I don't like either solution.
- tsewlliw 15y ago> How does this work for constructors? There's always static factory methods, for when constructors just can't do what you need.
- virmundi 15y agoBut doesn't this basically mean that my constructor has to allow for invalid states? Also, doesn't that mean that another object has the rules for what makes the first object valid? Isn't that a violation of separation of concerns?
- tsewlliw 15y agoI'm coming at this with Java semantics, apologies if that just doesn't work for you :) I'd make the constructor private, and move the validation into a public static factory method on the same class that returns an Either.
- T-R 15y agoPerhaps you could return an Either from the constructor, and then either have a special construct to handle Left: myObj = new Object() :{ cleanup() } or require dummy objects in case of failure: myObj = new Object() ?? new DummyObject() Admittedly less than optimal. The more I think about it, the more I think it's a bad idea... The first still means that you need a separate catch block for each statement. The second is essentially swallowing the exception. Aside from that, using Either in the return kills your ability to do method chaining, unless you build method chaining into an operator and have it propagate the Either (similar to bind).
- riffraff 15y agoI think I am missing something: is there any commonly used statically typed OO language that allows you to return a different type from the constructor? AFAIR even in scala you either use a factory method in a companion object or use "real" constructors.
- 0x0 15y agoIf Objective-C fits your definition of statically typed OO language, then I believe you can return whatever you want in the -(id)init constructor. The common idiom for implementing constructors in subclasses is to do "self = [super init]; if (self) { ... subclass constructor impl ... }; return self". Setting self to nil is a common use-case.
- ryanpetrich 15y agoObjective-C isn't a statically typed language, it is a dynamically typed one with static type annotations to make the compiler check common errors for you.