Against enforce()

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed Mar 16 18:55:39 PDT 2011


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



More information about the Digitalmars-d mailing list