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?
1 Answer 1
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.
$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.