I have a class with a method that will be called multiple times over an object's lifetime to perform some processing steps. This method operates on a mixture of immutable (does not change over the lifetime of the process) data and data that is passed as an argument. The immutable data is comparatively expensive to calculate, so I would like to cache it.
class Sample
{
public function process($data)
{
$immutable = $this->getImmutable();
$this->processImplementation($immutable, $data); // not interesting
}
}
How should getImmutable
be implemented?
Option #1 would be
public function getImmutable()
{
static $cache;
if ($cache === null) {
$cache = "not interesting";
}
return $cache;
}
Option #2 would be
private $_cache;
public function getImmutable()
{
if ($this->_cache === null) {
$this->_cache = "not interesting";
}
return $this->_cache;
}
Option #2 is of course better OOP, but what I like about option #1 is that the "implementation detail" $cache
is physically close to the only place where it is used. This means that it doesn't increase the mental load of someone reading the code unless that someone decides to read the body of getImmutable
, in which case the implementation detail has become important.
In my mind, this purely practical argument is stronger than theoretical purisms.
I am also aware that the static
version shares the cache across all instances of the class, which option #2 does not (and that's a good thing). However this is not an issue because
- no more than one instance of the class will be created per process
- PHP is not multithreaded so the shared cache will not be a problem even when unit testing
Is there some other argument for option #2 that could tip the scales?