string <-> null/bool implicit conversion
Jonathan M Davis via Digitalmars-d
digitalmars-d at puremagic.com
Fri Aug 21 08:07:08 PDT 2015
On Friday, 21 August 2015 at 14:34:49 UTC, Steven Schveighoffer
wrote:
> On 8/21/15 10:12 AM, Jonathan M Davis wrote:
>
>> I know full-well that that's what you're doing, but that's not
>> what your
>> average programmer is going to expect. Anyone not intimately
>> familiar
>> with the ins and outs of D's arrays - or even a D programmer
>> who's not
>> paying really close attention - is likely to think that arr !=
>> null is
>> checking whether the array is null - not whether the array is
>> empty. And
>> if I see code like that, I'm going to assume that the
>> programmer who
>> wrote the code really wanted was !is null but either made a
>> mistake or
>> didn't understand the difference between !is and != in this
>> context.
>
> This is a very bad assumption. null is just a name for a
> pre-defined empty array, perfectly legal to compare with.
>
> Whenever I see "arr is ...", I would consider that to likely be
> a mistake warranting further investigation. Because an array is
> synonymous with its elements, not it's pointer. There obviously
> are cases where the pointer value is important, but very very
> rarely do you care that an array's pointer *and* it's length
> are identical. != does not warrant the same scrutiny, because
> it doesn't care about the pointer value.
Yes, but null is pretty much synonymous with pointers. Almost
anyone who sees null is going to be thinking pointers. The way
that we treat null with arrays is just plain bizarre. It works,
but it's not what anyone coming to the language expects, and I
think that explicitly using null to mean anything other than null
is just plain error-prone. Yes, using ==/!= to compare an array
with null is going to check for empty rather than check the
pointer, which is consistent with how it's going to work when
comparing with another array which is null, but how many
programmers are really going to look at arr == null and think
that it's checking whether the array is empty? If they have
enough experience in D _and_ they're paying enough attention,
then they'll understand what's going on and catch it, but there's
no reason to introduce that level of confusion in the first
place. IMHO, it's far better to just be explicit about it and do
arr.empty - or arr.length != 0 if you don't want to pull in
std.array. I see zero benefit in doing arr == null and only an
invitation to confuse people - be it someone who doesn't
understand all of the intricacies of D's arrays or a developer
that's working too late. Using arr.empty just eliminates all of
that confusion and makes the code clear.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list