in reply to Re: How could we "implement" Open Classes in Perl ?
in thread How could we "implement" Open Classes in Perl ?

I think I like them because you don't have to spend all that time on design patterns.
  • Comment on Re^2: How could we "implement" Open Classes in Perl ?

Replies are listed 'Best First'.
Re^3: How could we "implement" Open Classes in Perl ?
by BrowserUk (Patriarch) on Jun 27, 2008 at 07:59 UTC
      I like to design as I code. I'm not really the adept of "thinking first,and coding second" :)

        You are still coding your methods in your source code, so they are built at compile time, not run time, so you are not utilising any benefit of "open classes".

        In order to make effective use of open classes, you need to dynamically determine not just the code that sits behind any given method name, but what that piece of code actually does. That is:

        If you have something like:

        package class; sub metthod { ... } sub constructor or method { ... if( some condition) { *{class::method} = sub { ... }; } }

        Then the function of both possible implementations is being determined at compile-time. The only runtime decision is which implementation is associated with the method named 'method'. And that means that you could just as easily, and far less obscurly, place both implementations inside alternate paths of an if statement conditional upon 'some condition' and the result would be exactly the same. You have made no useful use of the 'open class' concept.

        In order to make use of open classes, the actual code that sits behind the method name has to be generated at runtime, based upon some piece of information not available at compile-time, not just selected. And I have yet to see a single instance of this in a real program.

        As an example of what I mean, you might code the read method of a 'secure' transmission protocol so:

        sub read { my( $self, $socket ) = @_; my $key = <$socket>; my $transform = $self->getTransform( $key ); *{__PACKAGE_::read} = eval <<"EOC"; sub { (my \$in = <\$_[ 1 ]>) =~ tr[\x20-\xfe][$transform]; \$in; } EOC return $self->read( $socket ); }

        The first time this method is called, it reads a key from the socket argument and derives a decryption transform from that key.

        It then replaces itself with a method that uses that derived transform to decode all subsequent input from the socket. As the tables for tr are built at compile time, but the key is not available until runtime, there is no simpler way of doing this.

        This would be an effective use of an open class, but I've yet to see a live example that couldn't be replaced with a compile-time equivalent.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.