Wikis & learning

Use a named factory to build a value

A static factory method can explain the representation it accepts. A class constant can name an internal conversion factor shared by every instance.

A static factory method can explain the representation it accepts. A class constant can name an internal conversion factor shared by every instance.

Walkthrough

The constructor is private so callers choose the named factory. Keeping the stored amount in integer cents avoids binary floating-point rounding during the multiplication in this example.

PHP example

<?php
class Amount {
    private const CENTS = 100;
    private function __construct(private int $value) {}
    public static function whole(int $units): self {
        return new self($units * self::CENTS);
    }
    public function cents(): int { return $this->value; }
}
echo Amount::whole(3)->cents();

Expected output

300

Change and check

Construct values for zero and three whole units. Think about how you would handle a decimal amount without silently discarding a fraction.