Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Do you know where your variables are?
 
PerlMonks  

Introducing Class::InsideOut

by xdg (Monsignor)
on Jan 09, 2006 at 17:01 UTC ( #521997=perlmeditation: print w/ replies, xml ) Need Help??

Building on several recent threads on inside-out objects, I've recently released an "alpha" version of a simple, safe and streamlined toolkit for building inside-out objects called Class::InsideOut.

Compared to other inside-out object building modules already on CPAN, this module aims for minimalism and robustness:

  • Does not need to be subclassed

  • No source filters

  • No attributes or CHECK blocks

  • Doesn't leak memory

  • Overload-safe

  • Thread-safe (for Perl 5.8 or better)

  • Supports any underlying object-type, including direct foreign inheritance

  • Has hooks for Storable to serialize scalar, array or hash-based inside-out objects

The goal of Class::InsideOut is to provide the minimal support necessary for creating safe inside-out objects. All other implementation details, including writing a constructor and managing inheritance, are left to the user. More advanced builders could be written on top of Class::InsideOut, of course.

For example, here is a very simple class:

package My::Class; use Class::InsideOut qw( property register id ); # declare a lexical property hash with 'my' property my %name; sub new { my $class = shift; my $self = \do {my $scalar}; bless $self, $class; # register the object for thread-safety register( $self ); } sub get_name { my $self = shift; # optional 'id' as alias to Scalar::Util::refaddr return $name{ id $self }; } 1; # modules must be true

For a more complete description of the philosophy, design, and interface, please see the Class::InsideOut documentation. The documentation includes a comparison to other inside-out object generators on CPAN. Of the various modules, the one that is closest to this is Object::InsideOut, which I recommend for a more full-featured approach.

(At the risk of straining a simile, perhaps, Class::InsideOut is supposed to be like a Honda Civic -- basic and dependable. Object::InsideOut is more like a Porsche -- designed for speed and style. I see the two as complements, not competitors.)

As the basic inside-out feature set is working and code-coverage is high, Class::InsideOut needs some field testing. I encourage fellow monks to download it, give it a test drive and offer some feedback. To those with enough expertise to find implementation weaknesses, I would particularly welcome your insights. (In particular, I'd greatly appreciate if someone could give it a spin under mod_perl and some Storable-compatible session manager, as I don't have an environment for those handy to test.)

Thanks!

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Comment on Introducing Class::InsideOut
Select or Download Code
Re: Introducing Class::InsideOut
by merlyn (Sage) on Jan 09, 2006 at 17:16 UTC
      Too many people thinking of Perl6 already. Yes, I've reported it, but been ignored apparently.

      That's 'cause you don't have enough XP. ;-)

      Yes, I've reported it, but been ignored apparently.

      FWIW, I've pointed out that same thing to the author of Object::InsideOut in Re: What is method () ?. His response there isn't entirely satisfactory, but it's perhaps better than no response at all.

        Likewise, I had an exchange on AnnoCPAN. I don't think it really hurts anything as long as the rationale for it is explained clearly and it's not copied blindly. Though, as my code attests, I don't favor the style, personally.

        -xdg

        Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      Can someone explain what this is about? the difference in syntax? and its relation to Perl6? Thanks.

        From my AnnoCPAN comment:

        These package blocks are only necessary if multiple classes are being defined in the same file, or there are mixed classes and code. (Which is what the synopsis shows.) They keep the lexical variables for each in separate scopes. If a single file holds only a single class, the enclosing file scope is sufficient and the braces aren't necessary.

        Perl 6 uses a class declaration with braces. From Apocalypse 12, here's an example of a Perl 6 class:

        # A Perl 6 class class Point { has $.x; has $.y is rw; method clear () { $.x = 0; $.y = 0; } }

        Since a Perl 5 package statement isn't exactly the same as a Perl 6 class statement, it's potentially confusing to write this:

        # A Perl 5 class package Point; { use Object::InsideOut; my @x :Field; my @y :Field('Accessor' => 'y'); sub clear { my $self = shift; $x[$$self] = 0; $y[$$self] = 0; } }

        In Perl 5, the braces are just defining a lexical scope, which inside-out objects happen to use to create encapsulation. But unless there are other lexical scopes in the file that defines the Perl 5 class, the braces aren't necessary and writing them on the same line may make people think it's related to the package statement. As an example, consider this version with the braces moved:

        # A Perl 5 class -- take 2 package Point; { # same guts as before } # still part of package Point outside the braces # but @x and @y can't be seen from out here

        Now consider what happens if the package statement is inside the braces instead:

        # A Perl 5 class -- take 3 package Foo; # just for later clarity { package Point; # same guts as before } # Back to package Foo out here

        -xdg

        Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      why, exactly, is that syntax a mistake?
        It's not a mistake. It's a preference. All three styles (package declaration outside the block, package declaration inside the block, and no block at all with file scope) work, and all have their own little pros and cons (none of which rise to the significance of such 'mistakes' as coding errors, syntax abuses or obfuscations).

        Unfortunately, such relative trivialities sometimes get overly exaggerated (even to the point of becoming flame wars); thereby distracting everyone from important topics such as xdg's excellent contribution to the Perl community which he has announced in this thread.


        Remember: There's always one more bug.
Re: Introducing Class::InsideOut
by phaylon (Curate) on Jan 10, 2006 at 14:51 UTC
    I really like the approach. And my first thought was 'Additional functionality could be injected with Traits.' Is there a possibility of introspecting the class? Such as retrieving "registered" properties?

    Ordinary morality is for ordinary people. -- Aleister Crowley

      Yes, traits should integrate into this well, at least conceptually. (I'll have to review Class::Trait more closely before commenting on any potential compatibility with that specific implementation.)

      Some introspections should be possible, but the property names aren't directly available at the moment -- only references are saved away. However, if accessors are created, those methods would define what is available to a trait. (Traits would be in a different lexical scope and would have to use accessors.)

      Getting the property names for accessors is actually a bit tricky and would involve either ugly syntax (property name => my %name) or else using something like PadWalker to find the name from the reference. I haven't worked out an elegant/portable approach yet.

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: Introducing Class::InsideOut
by Anonymous Monk on Feb 12, 2006 at 14:46 UTC

    I like the minimalistic approach and the tendency not to force the user into a straight-jacket.

    My one point of critique is: ->new doesn't only create but also initializes objects. This is wrong, simply because (in an inheritance situation) you want to create only one object (call ->new, bless it into a class), but initialize the object to work with not only the class itself, but one or more superclasses. If creation and initialization are forced together, that gets awkward.

    If you separate creation and initialization, ->new can become a generic method (like DESTROY), which is inherited by all classes in the hierarchy and never overridden. The initializers are left entirely to the client. On a side note, that would allow you to do object registration in ->new (or not do it if threads aren't enabled), and not bother the user with it.

    A minor point of critique is that you seem to be cache-ing inheritance data that could change at run time. The cache could get out of sync.

    I'd also like to point out a novel (to my knowledge) method to do desctruction of inside-out objects. Instead of following the inheritance tree, you can look at the object and see which classes it is initialized to. With a little collaboration from the user, you can see that by inspecting which field hashes have existing keys with the object's id. The field hashes of these classes must be cleared (and their DEMOLISHers called).

    It is up to the initialization methods to set up an object for all classes it inherits from (possibly following the inheritance tree). DESTROY only has to follow suit. In my view, this is how it should be.

    I have put up a demo of these features under http://www.tu-berlin.de/zrz/mitarbeiter/anno4000/clpm/InsideOut/ (no, I'm not putting this sketch on CPAN).

    I'll try to keep an eye on this place, but I'd be grateful for an email-ed ping to mailto:anno4000@mailbox.tu-berlin.de if someone comments on this.

    Regards, Anno

    20060212 Janitored by Corion: Added formatting

      Sorry for the formatting of my previous post. The preview looked decidedly different. What happened to my paragraphs? Anno
      My one point of critique is: ->new doesn't only create but also initializes objects. This is wrong, simply because (in an inheritance situation) you want to create only one object (call ->new, bless it into a class), but initialize the object to work with not only the class itself, but one or more superclasses. If creation and initialization are forced together, that gets awkward.

      By design, Class::InsideOut doesn't provide new(). Users are free to combine creation and initialization, or to separate them, based on personal preference and design needs. Somewhere along the line, register() has to be called, but that's the only requirement. I'm supporting of people subclassing Class::InsideOut to provide a new/init structure. (I intend to do one myself when I get a chance.)

      A minor point of critique is that you seem to be cache-ing inheritance data that could change at run time. The cache could get out of sync.

      Technically, it caches at run-time at the point of first use. E.g., the first time DESTROY is called, the cache is built. Hopefully, at that point, any run-time @ISA manipulations are done.

      I'd also like to point out a novel (to my knowledge) method to do desctruction of inside-out objects. Instead of following the inheritance tree, you can look at the object and see which classes it is initialized to. With a little collaboration from the user, you can see that by inspecting which field hashes have existing keys with the object's id. The field hashes of these classes must be cleared (and their DEMOLISHers called).

      By ignoring @ISA you wind up having to search through all registered properties. From looking at your code, it looks like your approach searches through all properties to generate a list of classes and then iterates back over those classes to do the destruction. That's seems to me like a potentially big computational hit for a DESTROY method -- particularly if lots of inside-out classes exists and if lots of objects are created and destroyed.

      Class::InsideOut uses @ISA and the cache to try to minimize the inevitable overhead of DESTROY. While the caching might be a little too aggressive a form of early optimization, I think @ISA is a good way of avoiding having to do an exhaustive search.

      That said, I think your code is an interesting start at an alternative. If you decide to continue developing it, I suggest you look at the slides from my talk on inside-out objects for ideas on some of the incremental features you may want to support. (You may find that doing so will complicate the elegance of your design.)

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        I (Anno) wrote:
        My one point of critique is: ->new doesn't only create but also initializes objects...

        To which you (xdg) replied
        By design, Class::InsideOut doesn't provide new()...

        Right. It looks like I misunderstood your design when I wrote that. Main point of critique withdrawn.

        However, I think I would go so far and enforce the separation of creation and initialization. As a designer, it gives you one more point of control (->new is your baby now). Your users fully control object construction through their ->init methods.

        This may be the zealotry of the newly-converted (you monks will understand). I have written functional OO Perl where ->new initialized its object like everyone else's ->new, and I thought I was doing fine. Now I find that with the separation many things fall into place, not only in coding practice, but conceptually too.

        With inside-out classes, it is the effect of the individual ->init calls (one for each class the object is going to be used with) that DESTROY must undo. The result of ->new takes care of itself, like with standard objects.


        Anno:
        I'd also like to point out a novel (to my knowledge) method to do desctruction of inside-out objects. Instead of following the inheritance tree, you can look at the object and see which classes it is initialized to...

        xdg:
        By ignoring @ISA you wind up having to search through all registered properties...

        It's not that bad. I walk through all registered classes, checking a single hash key for existence. That tells me which classes the object has been initialized to, presumably the same set an @ISA analysis would return. There are situations where this gets inefficient (many classes, little inheritance). The method can be refined so that the classes an object is initialized to are known without a search, but that burdens initialization a bit. It's a tradeoff over the life-cycle of an object.

        My point is that DESTROY should read things off the object. If the inheritance tree is allowed to change, an object could have been constructed according to one situation, but be destroyed in another. Even relying on the live @ISA tree could get destruction wrong in that case.

        xdg:
        I suggest you look at the slides from my talk on inside-out objects for ideas on some of the incremental features you may want to support. (You may find that doing so will complicate the elegance of your design.)...

        There speaks the saddened voice of experience. Don't I know it! At the moment I much prefer churning out pretty little sketches of various designs, mostly for my own edification.

        As for additional features, before seeing your slides I'm thinking of a dump/stringification/persistence function (dump a necessity, persistence is good). I might add an "accumulate" feature (call methods of a name for a set of classes, with a way to specify the inheritance ancestry for that set). I'd have to look at its utility. It gets complex when different parameters must be passed to different classes. Oh, and the threads-issue must be addressed somehow. I'll look at your slides and see what else comes up.

        Regards, Anno

      I'll try to keep an eye on this place, but I'd be grateful for an email-ed ping to mailto:anno4000@mailbox.tu-berlin.de if someone comments on this

      If you register then you can turn on the /msg me on reply to my post and your monitoring would be as simple as visiting the Message Inbox occasionally to see what replies you have.

      Who knows you might even end up posting a second time Anno. :-)

      BTW, I strongly agree on the seperation of initialization and construction in perl classes. Assuming that new() will never be overloaded, but that init() might be is IMO one of the better ways to handle perl OO.

      ---
      $world=~s/war/peace/g

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://521997]
Approved by Corion
Front-paged by valdez
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (19)
As of 2014-04-16 14:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (427 votes), past polls