Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to return an empty string or null value

If I were writing the below method (for example) is it considered good practice to either:

A: return an empty string if the document didn't exist?

B: return a null value?

Having done a lot of Java, and methods in Java requiring a return type, I'm under the impression it is best practice to return a consistent type, is this also the case in PHP or is it better to return a null value instead?

DocumentClass
{
    public function getDir($documentId)
    {
        /* Code to get location of document  */
        return (file_exists($document) ? $document : '');
    }
}

if (!empty($documentClass->getDir(5))
{
    /* Do this */
}

If it is better to return a null value, can you explain why?

like image 688
Joseph Woodward Avatar asked Aug 15 '12 13:08

Joseph Woodward


People also ask

Is it better to return null or empty string?

The function is meant to return a single value, such as findPerson(). If it was designed to return a collection e.g. findAllOldPeople() then an empty collection is best. A corollary of this is that a function which returns a collection should never return null.

Why use null instead of empty string?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters.

Should I return null or empty array?

Some functions return arrays, which appear like a pointer to an object. However, if a function has the option of returning an array or indicating that a valid array is not possible, it should not return NULL . Instead, the function should return an empty array.

Is a null string the same as an empty string?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


2 Answers

PHP convention

Return boolean FALSE.

OOP approch

Throw an exception. Also you should use a method dir_exitsts (or any other name you like) that only returns boolean (true of false). And use it before calling getDir

There really no specific rule for this. Its completely up to you.

I follow PHP way which is returning false.

like image 61
Shiplu Mokaddim Avatar answered Sep 20 '22 12:09

Shiplu Mokaddim


What would you do with this returned value? Should this signal a logical error, illegal input - or just some edge case?

In both 'error' cases I'd stick with exceptions instead of some fringe return values - especially because PHP is weakly-typed language, and it's way too easy to mix NULL and '' in some (stupidly) written == expression.

For edge cases perhaps I'd stick with FALSE as a value to return. It's, to my mind, a bit broken approach (check this link for the truly maddening example), but at least it's a common idiom in PHP.

like image 27
raina77ow Avatar answered Sep 18 '22 12:09

raina77ow