(This is kind of QA related - bear with me and I'll get to that)

Is there a name for inheritance when applied to objects rather than
classes? For example, assume I have a class that formats HTML elements
for a web form. For whatever reason I only want to have one instance of
this class per form. I might write something like this:

    my $form = WebForm::new;

    $form->set_width(30);
    $form->input('name', 'Enter you name');

    $form->set_width(10);
    $form->input('age', 'Enter your age');

The set_width calls are a bit ugly. Obviously I could just arrange to
pass the width to the calls to input() - but that gets cumbersome if I
have more parameters than just the width to set.

Instead I'd like to be able to write:

    my $form        = WebForm::new;
    my $wide_form   = $form->variant( { width => 30 } );
    my $narrow_form = $form->variant( { width => 10 } );

    $wide_form->input('name', 'Enter you name');
    $narrow_form->input('age', 'Enter your age');

There's still only one WebForm object: $wide_form and $narrow_form are
proxies for $form that modify its behaviour. It's a bit like currying
but for objects rather than functions.

The QA angle: In the first example $form can be in one of three states
depending on where you look at it. As the code became more complex and
more fields were added and then maybe reordered it'd be hard to keep the
formatting associated with the fields it's supposed to affect.

In the second example you have multiple handles on the same object with
its precise behaviour depending on which handle you call it by. The
WebForm and its two proxies are immutable so you can expect them always
to behave the same regardless of the ordering of the calls to input().

In some ways it's similar to MVC with $wide_form and $narrow_form being
two views attached to the $form controller. The difference is that the
two views actually inherit their behavior from the controller and can be
used interchangeably with it.

--
Andy Armstrong, hexten.net

Reply via email to