Consider class Crate
that is a value object. Crate represents a valid 3-dimensional box.
In constructor I validate the given parameters, and I throw an exception, if supplied dimension parameters are invalid:
class Crate
{
protected $length, $width, $height;
function __construct(float $length, float $width, float $height)
{
if ($length <= 0 || $width <=0 || $height <=0)
throw new RuntimeException("Invalid Dimension");
$this->length = $length;
$this->width = $width;
$this->height = $height;
}
function getDimensions()
{
echo $this->length . 'x' . $this->width . 'x' . $this->height;
}
}
In my project I have a need to display dimensions of several crate box configurations. Namely, there is a showCrates
method that accepts an array of Crate
and then uses that array to display each Crate's dimensions, and other info.
function showCrates(array $crates)
{
foreach($crates as $key => $crate)
echo 'Crate #' . $key . ':' . $crate->getDimensions() . PHP_EOL;
}
showCrates
works great when all parameters given to all Crate
objects are valid. However, when a Crate
object throws an Exception on an invalid parameter, code execution stops.
I want to be able to keep the execution going and still show the valid crates, but for invalid crates to have a message saying "Crate at index i
was invalid".
Sample output that I expect is:
Crate #1: 2x5x9
Crate #2: 1x3x4
Crate #3 is invalid, because supplied dimensions were: 0x0x0
Crate #4: 5x6x3
Question
I am looking for a way that will let me display the above output without modifying Crate
object itself.
Potential Solution that I am rejecting:
One way to solve my question is to allow invalid Crate
objects and have an error boolean flag inside them stating whether a Crate
is valid or not. Then I can keep showCrates
method signature - to accept an array of Crate
object - but modify it to check first, whether a Crate
is valid, and to display desired output accordingly.
However, ideally I would like to NOT modify my Crate
object unless there is a very strong argument to do so. I have constructed Crate
object to be an immutable value object that can only exist if parameters supplied to it are valid, and to otherwise throws an Exception. As to why, I believe that this way the Crate
is more easily testable and there are no extra checks to see whether or not Crate
is valid.
Sample Calling Code
class CrateRequestHandler
{
function handle(ServerRequestInterface $request)
{
// mocked up data from Request
// this is sample data for showcase purposes only
// it usually supplied by user or from database
// and it is impossible to tell ahead of time
// if it will be correct for Crate purposes
$crates = array();
$crates[0] = new Crate(2, 5, 9);
$crates[1] = new Crate(1, 3, 4);
$crates[2] = new Crate(0, 0, 0);
$crates[3] = new Crate(5, 6, 3);
// send to View
$this->showCrates($crates);
}
function showCrates(array $crates)
{
foreach($crates as $key => $crate)
echo 'Crate #' . $key . ':' . $crate->getDimensions() . PHP_EOL;
}
}