|Problems? Is your data what you think it is?|
Re: inside-out objects using arrays?by xdg (Monsignor)
|on Sep 18, 2005 at 04:36 UTC||Need Help??|
What are you trying to achieve with this approach? There are many ways to make "inside-out" objects. The core idea is just that the object (the blessed reference) either (a) contains or (b) is itself (via it's memory address) an index to some other data storage container. That storage container could be almost anything, and accessed in almost any way.
One reason that inside-out objects are interesting people lately is that it's possible, even easy, to make the container a "private" lexical and have the accessor reach it via a closure. On the other hand, you can make the storage global and do some really wild aliasing, too. (See my Object::LocalVars if you want to bend your brain.) It all depends what you're trying to accomplish.
I'm not sure what the array storage gets you over a hash -- maybe a bit of speed, but extra hassle dealing with reclaiming memory as other posters have noted. One downside to the array is that it's possible to manipulate the index inside the blessed reference and potentially peek into other objects. I think Conway talks about this in Object Oriented Perl.
With a hash and "unique" indices, you avoid that problem. On the other hand, as I pointed out in 'Threads and fork and CLONE, oh my!', using a memory address as a unique index breaks under threads or a pseudo-fork on Win32 unless you use Perl 5.8 and go to some pains with CLONE and again sacrifice efficiency for book-keeping.
I'm not convinced there's a "right" way to do inside-out objects. Until Perl 6 anyway. (/me grins)
I'm currently experimenting in a couple ways. With lots of attributes, keeping each in a separate hash like how Class::Std does is costly for destruction. I've been speculating whether the right approach is to keep one hash keyed on the index (needed for CLONE anyway), and have the contents be a hash reference with the keys being the individual attributes. Then DESTROY only needs to clean up one reference in the master hash, and let Perl's garbage collection take care of the rest.
On the more bent side, I'm considering that approach but using anonymous symbol table refs, so I can get that elegance in cleanup and still use the local aliasing trick in Object::LocalVars. (Why do I feel like I'm on the path to the Dark Side when I say that...)
So... if you want to use arrays for your inside-out objects, you can -- but know why you're doing it and what that gains you and what you give up in doing so.
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.