Consider Crate::addLength() in the following code:
class Crate
{
protected $length, $width, $height;
function __construct(float $length, float $width, float $height)
{
$this->length = $length;
$this->width = $width;
$this->height = $height;
}
function addLength(float $length): Crate
{
return new self($this->length + $length, $this->width, $this->height);
}
}
I am concerned that Crate object creating a Crate object is a violation of Single Responsibility Principle (SRP). Crate object duties is to keep dimensions of the crate. Creating another crate object seems like introducing extra responsibilities to a class that already has responsibilities.
With that in mind, how to I make the code better?
The directions I think I can go are
1) Is it better to just instead increase the length of the Crate?
function addLength(float $length): void
{
$this->length += $length;
}
When doing so however, my crate becomes 'stretchy', which is typically not done in real life. Instead, a new crate is constructed with given measurements.
Thus,
2) Is it better to instead delegate object creation to a separate class?
class CrateService
{
function addLength(Crate $crate, float $length): Crate
{
return new Crate($crate->GetLength() + $length, $crate->getWidth(), $crate->getHeight());
}
}
That seems to work, even if a little cumbersome - we basically call every crate's dimension individually and add the adder length, and create a new crate.
Crateclass. Set the color of the crate? Fill it with stuff? Who knows? You must have other plans for this class than just setting dimensions. Objects in a program don't always follow the same rules as objects in real-life. A 'stretchy' crate is not a problem, unless there's something else that prohibits it. \$\endgroup\$Crateobject. \$\endgroup\$