Against enforce()
Daniel Gibson
metalcaedes at gmail.com
Wed Mar 16 19:03:23 PDT 2011
Am 17.03.2011 02:55, schrieb Andrei Alexandrescu:
> On 03/16/2011 08:50 PM, Daniel Gibson wrote:
>> Am 17.03.2011 02:07, schrieb Andrei Alexandrescu:
>>> On 03/16/2011 06:45 PM, bearophile wrote:
>>>> - Where it is used it usually doesn't give a more meaningful exception
>>>> like WrongArgumentException, etc. I don't want a deep hierarchy of one
>>>> hundred standard exceptions, but I think some standard exceptions for
>>>> the most common mistakes, like wrong arguments, etc, are better than a
>>>> generic enforce(), especially for a standard library code that is
>>>> meant to be written with care and to give better error
>>>> messages/exceptions.
>>>
>>> enforce helps such idioms, does not prevent them. From the docs:
>>>
>>> ===============
>>> T enforce(T)(T value, lazy Throwable ex);
>>>
>>> If value is nonzero, returns it. Otherwise, throws ex.
>>> ===============
>>>
>>
>> Really?
>> using enforce with a custom throwable saves *one* char:
>> enforce(foo, new BlaException("bad!"));
>> if(!foo) throw new BlaException("bad!");
>> or are there other merits?
>
> enforce is an expression that returns its argument so it's composable.
>
> Andrei
>
You're right. I just realized it and wanted to reply that correction to
myself but you were faster :)
I agree, that *is* helpful.
A side note: The documentation says the value is returned if it's
"non-zero".
enforce() also throws on null (for classes, probably also for pointers)
and false (for bool..) - this should probably be mentioned in the docs ;-)
Cheers,
- Daniel
More information about the Digitalmars-d
mailing list