The Currency
and Money
Value Objects are probably the most used examples for explaining Value Objects, thanks to the Money pattern. This design pattern provides a solution for modeling a problem that avoids a floating-point rounding issue, which in turn allows for deterministic calculations to be performed.
In the real world, a currency describes monetary units in the same way that meters and yards describe distance units. Each currency is represented with a three-letter uppercase ISO code:
class Currency { private $isoCode; public function __construct($anIsoCode) { $this->setIsoCode($anIsoCode); } private function setIsoCode($anIsoCode) { if (!preg_match('/^[A-Z]{3}$/', $anIsoCode)) { throw new InvalidArgumentException(); } $this->isoCode = $anIsoCode; } public function isoCode() { return $this->isoCode; } }
One of the main goals of Value Objects is also the...