HN Simulatornew | past | comments | lists | submitlogin

> Because the semantics of a constructor is to bring an object into a valid state and you don’t expect it to perform any functionality.

No, I expect it to perform the functionality of bringing the object into a valid state - whatever functionality that takes. And if it can't, then throwing is the next option, because it's preferable to having an object in an invalid state.



What if the object can be invalidated asynchronously after the constructor has completed and before you get to use the object? For example by a remote connection dropping? You have to check that it still works anyway: you can’t assume it by construction.

I prefer to have constructors that can’t go wrong (except trivially for OOM that ends the whole process), and then manage their dynamic state after construction.


Well, what if a valid object has to have a semaphore, because it can be accessed by things from multiple threads, and the OS has a limited number of semaphores that it will create? The object won't be in a valid state without a valid semaphore, so the constructor can fail. (Or, if you want, the semaphore's constructor can fail, but that will mean that this object's constructor also fails.)

Look, for your problem, you probably want to do what the fine article said - to have "invalid connection" be a valid state of the object.


I’d initialize the semaphore and any other things that could fail in a post-constructor setup/startup method. It’s a little ugly and it violates RAII, but I think it’s worth it on balance. So yes, I’m agreeing with you that’s how I’d do it.


I've done it that way at least once. But, personally, I prefer RAII, rather than a "half-constructed" state.




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

Search: