DEV Community

[Comment from a deleted post]
Collapse
 
aidantwoods profile image
Aidan Woods • Edited

I'd respectfully disagree that null is bad. Not being able to return an object isn't always an error. Sure sometimes it is, but sometimes it is an implementation detail that can't be known ahead of time, in which case calling the function is more like saying: "If you've got a burger, I'd like it.". Than your example of "Give me a burger".

As an example use case, in a WIP parser I'm writing, I ask specific objects which have declared a marker if they can interpret an element from that marker position. If they can't that's fine, but if they can I'd like to add it to the pool of elements that can be considered at that point.

With this design pattern, there is no reason to throw an exception if the element cannot be parsed, because it was a question I didn't know the answer to to begin with.

See: github.com/Parsemd/Parsemd/blob/a7...

private function findNewInline(string $marker, Line $Line) : ?array
{
    $Inlines = [];

    if (array_key_exists($marker, $this->InlineMarkerRegister))
    {
        foreach ($this->InlineMarkerRegister[$marker] as $handler)
        {
            if ($Inline = $handler::parse($Line))
            {
                $Inlines[] = $Inline;
            }
        }
    }

    return empty($Inlines) ? null : $Inlines;
}
Enter fullscreen mode Exit fullscreen mode

TL;DR: IMO if you find returning null is surprising, then you're asking the wrong question to begin with.

Collapse
 
mjrider profile image
Robbert Müller

and what would be wrong here by returning the empty array?

In this example the usage of null is bad. Because not finding anything is not an error/exception. And imposes extra (useless) checks on the callers code

Collapse
 
aidantwoods profile image
Aidan Woods

Perhaps I should have only included the code I was trying to highlight :p the particular line I was talking about was the the nullable named constructor:

if ($Inline = $handler::parse($Line))
{
    $Inlines[] = $Inline;
}

I'd agree that in the enclosing function, returning an empty array would be clearer/better. (The nullable is an artifact left over from that function previously only returning one object, which was then modified to return multiple). An array being a container object, has the privilege of an 'empty' or 'nothingness' state. Not all objects have this state (because it can not always make any sense) hence null (a separate type) being used to convey the 'nothingness' property.

In the nullable named constructor usage, no construction is not an error, and is a result that can only be determined by deferring expertise to the callee. Since it is not an error, there is also nothing to fix, the caller need not respond other than by continuing what it is doing. So IMO the exception is inappropriate for that particular usage.