Just a friendly reminder about using arrays in boolean conditions
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Nov 18 23:33:52 UTC 2024
On Monday, November 18, 2024 5:20:17 AM MST user1234 via Digitalmars-d wrote:
> Well I agree, even if that will take years to have .length tested
> instead of .ptr.
>
> Little story however: I've encountered a case where the explict
> check was also wrong.
>
> ```d
> module runnable;
>
> import std.stdio;
>
> void v(string s)
> {
> if (s.length) writeln("case length :`", s, "`");
> else if (s is null) writeln("case null :`", s, "`");
> else writeln("case not null but no
> length:`", s, "`");
> }
>
> void main(string[] args)
> {
> v("hello");
> v(null);
> v("");
> }
> ```
>
> The different semantics between `null` and `""` for strings is
> well illustrated here I'd say.
Yeah, I would consider it a code smell if code checks whether an array is
null. It _can_ make sense if you do something like have a function return a
null string on failure and a string with data (which could be empty) on
success, since then that function is directly returning null. However, then
you have to be concerned about the possibility of whether the code that
generates the non-null string to return could ever return null instead by
accident. So, ultimately, it's just better to use something like
Nullable!string instead if you want to distinguish between a string with a
value and a string without (and the same with any array type).
However, if for whatever reason, someone _does_ choose to have their code
differentiate between null and empty (much as I think that that's a terrible
idea), it's better if it's explicit about it rather than doing it implicitly
with something like if(arr), because then it's not clear what the programmer
was trying to do. It's possible that the programmer was intentially checking
for null, and it's possible that they meant to check for empty (I've seen
the latter case more frequently than the former even though that's not what
the code actually does). However, if the check is explicit - e.g.
if(arr is null) - then it's clear that the programmer intended to check for
null. Whether that then causes other problems is another matter, but at
least the intention of the code is clear, whereas it isn't if the check is
implicit. So, IMHO, if someone is going to do that check, it should always
be explicit - but of course, it would be better to simply not care whether
an array is null, because it takes very little to end up with a null array
when you didn't intend to (or a non-null empty one when you wanted null).
The rest of the language just isn't designed to care about null with arrays.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list