List of Phobos functions that allocate memory?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Feb 7 18:20:29 PST 2014
On Saturday, February 08, 2014 01:26:10 Meta wrote:
> >> You could always return an Option!char. Nullable won't work
> >> because it lets you access the naked underlying value.
> >
> > How is that any better than returning an invalid dchar with a
> > specific value?
> > In either case, you have to check the value. With the
> > exception, code doesn't
> > have to care. If the string is invalid, it'll get a
> > UTFException, and it can
> > handle it appropriately, but having to check the return value
> > just adds
> > overhead (albeit minimal) and is error-prone, because it
> > generally won't be
> > checked (and if it is checked, it complicates the calling code,
> > because it has
> > to do the check).
>
> We have had this discussion at least once before. A hypothetical
> Option type will not let you do anything with the wrapped value
> UNTIL you check it, as opposed to returning null, -1, some
> special Unicode value, etc. Trying to use it before this check is
> necessarily a compile-time error. This is both faster than
> exceptions and safer than special "error values" that are only
> special by convention. I recall that you've worked with Haskell
> before, so you must know how useful this pattern is.
The problem is that you need to check it. This is _slower_ than exceptions in
the normal case, as invalid Unicode should be the rare case. The great thing
with exceptions is that you can write your code as if it will always work and
don't need to put checks in it everywhere. Instead, you just put try-catch
blocks in the (relatively) few places that you want to handle exceptions. Most
of your code doesn't care. And if you validate the string before you start
doing a bunch of operations on it, then you don't have to worry about a
UTFException being thrown. Also, if code fails to validate a string for one
reason or another, the error gets reported rather than an invalid return value
being ignored.
As for returning Optional/Nullable dchar vs an invalid dchar, I don't see much
difference. In both cases, you have to check the return value, which is
precisely what you don't want to have to do in most cases. And decode has to
do the same work to check for valid Unicode whether it throws an exception or
returns a value indicating decode-failure, so why have the extra overhead of
having to check the result for decode-failure? Just let it throw an exception
in that case and handle it in the appropriate part of your code. Returning a
Nullable result or a specific bad value that you have to check rather than
throwing an exception only makes sense when it's expected that failures are
going to be frequent. If failures are infrequent, it's generally far better to
use exceptions, because it will lead to much cleaner, less error-prone code.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list