I've got a class which stores two data series like so. I need to do some complicated processing on each of these arrays, but for now we'll just get the average of each data series. I could either do this:
class DataMangler
{
private array $dataArrayA = [];
private array $dataArrayB = [];
// stand in for complicated calculation
private static function getAverage(array $dataArray): ?float
{
$sum = array_sum($dataArray);
$count = count($dataArray);
if (0 === $count) {
return null;
}
return $sum / $count;
}
public function getAAverage(): ?float
{
return self::getAverage($this->dataArrayA);
}
public function getABverage(): ?float
{
return self::getAverage($this->dataArrayB);
}
}
and then I can call each method individually.
Or I could add getters for each data array, and the caller has to pass them into the (now public) average calculation:
class DataMangler
{
private array $dataArrayA = [];
private array $dataArrayB = [];
// stand in for complicated calculation
public static function getAverage(array $dataArray): ?float
{
$sum = array_sum($dataArray);
$count = count($dataArray);
if (0 === $count) {
return null;
}
return $sum / $count;
}
public function getA(): array
{
return $this->dataArrayA;
}
public function getB(): array
{
return $this->dataArrayB;
}
}
$dataMangler->getAverage($dataMangler->getA());
Is there a rule of thumb for the better pattern?
(While writing this, I thought of a third option which is to make the dataArrays be fully fledged objects, which contain the logic for the complicated calculation. It still raises the question of getters for each DataArray object a la $dataMangler->getA()->getAverage()
or add wrappers around the average so it is still $dataMangler->getAAverage()
)
getA()
andgetB()
?DataMangler
is still required to mangle the two objects in one method (e.g. find average of differences for each index). And let's say no other class needs access to A and B in their raw values, only the mangled values, soget
ters wouldn't be present.