Wikis & learning

Keep presentation separate from conversion

An object that always creates its own formatter ties its results to one formatting choice. Inject a callable to choose that behavior at the boundary.

An object that always creates its own formatter ties its results to one formatting choice. Inject a callable to choose that behavior at the boundary.

How it works

This example expresses a formatter as a callable argument. A test can pass an ordinary closure and verify the result.

PHP example

<?php
function showCount(int $count, callable $format): string {
    return $format($count);
}
echo showCount(3, fn (int $n): string => $n . ' items');

Expected result

3 items

Try a variation

Supply another formatter that returns the number in square brackets. The counting function can stay the same.