[Israel.pm] An OOP Pattern Discovered by Accident

Shlomi Fish shlomif at iglu.org.il
Fri Jan 26 08:15:10 PST 2007


After I implemented the Math::GrahamFunction code to calculate the Graham 
Function using Perl ( 
http://search.cpan.org/~shlomif/Math-GrahamFunction-0.01/ ), I decided to 
translate the code to Common Lisp in order to learn Lisp better. So I started 
translating the methods of the classes, one by one.

Now, I have an SqFacts class that manages squaring factors, which for the 
purpose of our discussion are an increasing series of natural numbers. 
Furthermore, there's a Dipole class that inherits from it and manages two 
squaring factors - a result and a composition. Now in my Dipole Perl code I 
had the following declaration for the factors method:

<<<<<<<<<
sub factors
{
    my $self = shift;

    return $self->result()->factors();
}
>>>>>>>>>

And besides it similar declarations for some other functions:

<<<<<<<<<<
sub is_square
{
    my $self = shift;
    return $self->result()->is_square();
}

sub exists
{
    my ($self, $factor) = @_;

    return $self->result()->exists($factor);
}

sub first
{
    my $self = shift;

    return $self->result()->first();
}
>>>>>>>>>>>

Now when I implemented it in my lisp code, I implemented the SqFacts class, 
and tested it and then starting implementing the Dipole class. The factors() 
method was one of the first I implemented, and then I wrote two tests for the 
is_square predicate method, for both true and false returns. Surprisingly, 
they both passed without even implementing is_sqaure.

As it turned out, is_square and friends for the SqFacts class, used the 
factors() method and since factors() was already implemented and called the 
factors of the "result" property, then in Dipole, they just did the same for 
the factors of the "result". So I didn't have to implement the rest of the 
methods.

Thinking about it, I realised one can consciously use this scheme by working 
on an accessor and then over-riding this accessor in the derived class to 
point to the accessor of the containing class.

So we can do:

<<<<<<<<<<<<
class Account
{
	function account() { return self; }

	# Other functions that operate on account.
}


class B inherit from Account
{
	Account myaccount;

	function account() { return myaccount; }

	# We get the functions for free.
}
>>>>>>>>>>

Is this a known pattern in Object Oriented Programming and Design, and if so 
how is it called?

Regards,

	Shlomi Fish

---------------------------------------------------------------------
Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

Chuck Norris wrote a complete Perl 6 implementation in a day but then
destroyed all evidence with his bare hands, so no one will know his secrets.



More information about the Perl mailing list