Empty VS null array?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Oct 18 08:43:23 PDT 2013


On 10/18/13 3:44 AM, Regan Heath wrote:
> On Fri, 18 Oct 2013 00:32:46 +0100, H. S. Teoh <hsteoh at quickfur.ath.cx>
> wrote:
>
>> On Fri, Oct 18, 2013 at 01:27:33AM +0200, Adam D. Ruppe wrote:
>>> On Thursday, 17 October 2013 at 23:12:03 UTC, ProgrammingGhost
>>> wrote:
>>> >is null still treats [] as null.
>>>
>>> blah, you're right. It will at least distinguish it from an empty
>>> slice though (like arr[$..$]). I don't think there's any way to tell
>>> [] from null except typeof(null) at all. At runtime they're both the
>>> same: no contents, so null pointer and zero length.
>>
>> I think it's a mistake to rely on the distinction between null and
>> non-null but empty arrays in D. They should be regarded as
>> implementation details that user code shouldn't depend on. If you need
>> to distinguish between arrays that are empty and arrays that are null,
>> consider using Nullable!(T[]) instead.
>
> This comes up time and again.  The use of, and ability to distinguish
> empty from null is very useful.

I disagree.

> Yes, you run the risk of things like
> null pointer exceptions etc, but we have that risk now without the
> reward of being able to distinguish these cases.
>
> Take this simple design:
>
>    string readline();
>
> This function would like to be able to:
>   - return null for EOF
>   - return [] for a blank line

That's bad API design, pure and simple. The function should e.g. return 
the string including the line terminator, and only return an empty (or 
null) string upon EOF.


Andrei



More information about the Digitalmars-d mailing list