Google's Go & Exceptions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Jan 26 18:08:30 PST 2010


Nick Sabalausky wrote:
> "Justin Johansson" <no at spam.com> wrote in message 
> news:hjo31b$275o$1 at digitalmars.com...
>> Ary Borenszweig wrote:
>>> Walter Bright wrote:
>>>> Justin Johansson wrote:
>>>>> (1) For some reason (possibly valid only in an historic context), I 
>>>>> have this great aversion to throwing exceptions from inside C++ 
>>>>> constructors.  From memory, I once threw an exception from inside a 
>>>>> constructor
>>>>> with an early C++ compiler and wound up with stack corruption or 
>>>>> something like that, and consequently I developed the practice of 
>>>>> forever more avoiding throwing from inside a C++ constructor.
>>>> I'm a believer in the methodology that a constructor should be "trivial" 
>>>> in that it cannot fail (i.e. cannot throw). I'm probably in the minority 
>>>> with that view, but you shouldn't feel like you're doing the wrong thing 
>>>> when you stick to such a style.
>>> auto x = new BigInt(someString);
>>>
>>> How do you implement BigInt's constructor without being able to throw an 
>>> exception? Or would you do it like:
>>>
>>> auto x = BigInt.fromString(someString);
>>>
>>> to be able to throw? (just to obey the "no throw in constructors"... but 
>>> that's not as trivial as the previous form)
>> A factory method is the way to go.  Different languages give you
>> different means for achieving this design pattern but nevertheless
>> all such means make for the better factoring of code.
>>
> 
> Still within the context of this D BigInt example, what benefit does using a 
> factory method provide over a throwing constructor?
> 
> I've always seen factories as falling into one of two categories: 1. A hack 
> to get around a limitation in a language's constructor feature. or 2. Part 
> of a helper API (I guess the kids are calling those "facades" these days...) 
> for pre-configuring a new instance in a commonly-useful, but non-default 
> way.

Factories are mostly (imho) important in the fourth scenario: when you 
want to create an object from data.

Andrei



More information about the Digitalmars-d mailing list