Getter names for optional properties

Igor Budasov
WebDevOps
Published in
1 min readJul 11, 2018

Sometimes we have to deal with properties, which can be null

/**
* @var string|null
*/
private $description;

It’s fine, IDE will generate a getter for us

public function getDescription(): ?string
{
return $this->description;
}

It’s alright, it’s a common practice.
But I’d like to improve it.
The thing is — the name of the function lies.
It claims to return description but actually can return null as well.

The improvement

If we name the getter like getDescriptionOrNull().

Why?

  • It will be much closer to the truth and if will be easier to remember to handle null cases.
  • Also it will be easier to spot null-values propagation, which we want to avoid.
  • And even if it didn’t work, the one who’s gonna read the code later (let’s say code-reviewer), will spot the unhandled null-case and fix it according to BSR.

--

--

Igor Budasov
WebDevOps

A traveller. A drinker. A photographer. A blogger. An engineer.