Wikis & learning

Separate a public action from an object's private state

A public method can enforce rules about how private data changes. Clients can ask the object to perform a meaningful operation without manipulating its storage directly.

A public method can enforce rules about how private data changes. Clients can ask the object to perform a meaningful operation without manipulating its storage directly.

Walkthrough

The constructor supplies the first value. The add method rejects a negative increment and value returns the current count. Both operations leave the internal property name free to change later.

PHP example

<?php
class Counter {
    private int $n;
    public function __construct(int $start) { $this->n = $start; }
    public function add(int $amount): void {
        if ($amount < 0) { throw new InvalidArgumentException('Negative increment'); }
        $this->n += $amount;
    }
    public function value(): int { return $this->n; }
}
$count = new Counter(4);
$count->add(3);
echo $count->value();

Expected output

7

Change and check

Try adding a negative amount inside a try-catch block. Confirm that a rejected update has not changed the count.