Wikis & learning

Pass an interface into a report generator

An interface describes an operation that different classes can supply. Type the report function against the shared contract so it can use another implementation later.

An interface describes an operation that different classes can supply. Type the report function against the shared contract so it can use another implementation later.

Walkthrough

The formatter supplies its own rendering rule. The report depends only on its format method. Substituting a second formatter requires changing the object at the call site.

PHP example

<?php
interface LabelStyle { public function format(string $label): string; }
class BracketStyle implements LabelStyle {
    public function format(string $label): string { return '[' . $label . ']'; }
}
function reportTitle(string $label, LabelStyle $style): string {
    return $style->format($label);
}
echo reportTitle('Archive', new BracketStyle());

Expected output

[Archive]

Change and check

Implement a second formatter that surrounds its value with parentheses. Pass both implementations through the same report function.