Google's Go & Exceptions
Nick Sabalausky
a at a.a
Tue Jan 26 17:11:41 PST 2010
"Walter Bright" <newshound1 at digitalmars.com> wrote in message
news:hjnt03$1od9$1 at digitalmars.com...
> dsimcha wrote:
>> I've never understood the recommendation not to put complex logic in the
>> constructor.
>
> Complex logic is fine, just logic that cannot fail.
>
>> If you need complex logic to establish the class's invariant, or
>> need to initialize complicated immutable data structures, where else is
>> that logic
>> supposed to go?
>
> For example, allocating resources that might fail, can be done with a
> separate initialization function:
>
> auto c = new Class;
> c.create();
But then you're right back into manual-resource-management-land (yes, I
know, not for the GCed memory used to store the object, but besides that,
yea, manual-resource-management-land).
More specifically, you'll need to (or at least, *should*) set up a way for
the object to keep track of whether or not it's been properly initialized,
and then have all other accesses to it throw exceptions or something until
it is properly inited. And since it's useless until it's inited (or at least
not fully-useful), plus the fact that those "accessed an uninited Foo"
exceptions will be popping up in places *other* than where you
tried-to-create-the-Foo-but-forgot-to-init (which is where you'd ideally
want the exception to origninate from because that's where the real problem
is), this means we should ideally create a factory function to encapsulate
both the instatiation and initilization. And the constructor and init
function should now be private to force all instantiations through the safer
factory function.
And now, finally, our reward for all that work: We've reinvented the
wheel^H^H^H^H^H^H constructor! And with a syntax that's inconsistent with
all the other classes! Wheee!!!
More information about the Digitalmars-d
mailing list