1

We are dealing with a lot of null values, now and we are wondering if there are any standards for avoiding it at some places in the code.

For example I have this PHP code:

class X
    {
        function setName(string $name)
        {
            $this->name = $name;
        }
    }

$x = new X;

//Will throw exception
$x->setName(null);

Or I have this code:

class X
{
    function setName(string $name = null)
    {
        $this->name = (string) $name;
    }
}

$x = new X;

//Will not throw exception
$x->setName(null);

The last code is not really neat, because null should not be an allowed value, but it avoids the null pointer exception.

The alternative might be an if statement or a cast to string on each method call:

class X
{
    function setName(string $name)
    {
        $this->name = (string) $name;
    }
}

$x = new X;

if($value = $entity->getValue())
{
    $x->setName($value);
}


or 

$x->setName((string) $entity->getValue());

In my opinion the cast to string (last example) is the most readable solution.

Are there any rules or standards corporations follow to deal with this kind of errors? Or what should be the best way for object orientated programming?

  • 4
    I can't quite follow your intent. You write "because null should not be an allowed value". So to me it seems absolutely correct to get a null pointer exception if some code line does $x->setName(null); I'd definitely not want my program to silently continue after violating this constraint. And as PHP is typically interpreted, not compiled, there's no chance to get informed on the problem before executing. – Ralf Kleberhoff Sep 1 '17 at 8:32
  • In you first code example, no exception will get thrown. It simply sets the value. – Greg Burghardt Sep 1 '17 at 16:05
  • PHP will throw an exception: Exception: Argument 1 passed to X::setName() must be of the type string, null given, called in ... – Stefan Sep 2 '17 at 15:32
6

Don't avoid throwing exceptions and just carry on with invalid data, because then everything else has to carry on with invalid data. Things become increasingly meaningless when that happens.

You should throw at the earliest possible opportunity. If you require that $entity->getValue() never return null, then it should never be in a position to return null, because you have thrown somewhere earlier.

You then catch exceptions at the point where you can make progress without whatever threw. This may be at the top level, returning "404, no page today, sorry" if you have no other option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.