On Fri, Dec 10, 2004 at 11:05:32AM -0500, Abhijit Mahabal wrote:
: Consider a class (e.g., the hypothetical Geometry::Triangle) that can 
: have several attributes (side1, side2, side3, angle1, ang_bisector1, 
: side_bisector,  altitude1 and so forth), most of which will not be 
: needed for most instances of Geometry::Triangle.

This sounds to me more like a situation where you want to use mixins,
if you're thinking of it as different kinds of triangles.

But more likely, you just want a single private hash attribute that is
manipulated by as many publicly facing methods as you like.  Method
declarations don't cost you anything on a per-object basis unless they're
autogenerated from an attribute.  But a hash attribute autovivifies
just like any ordinary hash variable, and is probably clearer as well
to whoever has to read your code.

Alternately, you can still bless a hash as you typically do in Perl 5,
but then you get most of the problems of Perl 5 if you want to derive
from your class.

: I know how this can be done in P5. Using the layout "Hash" things are 
: easy. How can P6 deal with this, without allocating too much memory to 
: things that'd never get used? The layout "P6Hash" could come to the 
: rescue, but there is still the issue of syntax:
: 
: what exactly does C<has $.bisector1> do?

It does whatever the metaclass says "has" should do.  But you really want
to have a good reason for switching metaclass behavior from the default.

: IIRC, in the P6Opaque layout, 
: every instance of the class would have space the size of a PMC allocated 
: for it. This behavior is not needed for P6Hash, and it should just leave 
: attributes alone until they are assigned to (where defaults are also 
: "assigns").

I think the overhead might just be a pointer to a PMC, but I'm not
an expert on Parrot OO internals.

: In which case, maybe for that layout we can get away without declaring 
: all attributes, perhaps? (Since the declaration does nothing except help 
: the parser).

The layouts are mostly intended to help in detecting impedance mismatches
between different languages' objects.  Doubtless you can play games with
different layouts within Perl 6, but you should recognize that you'll run
into the same issues as you get with cross-language inheritance: you'll
probably end up with inheritance being emulated by delegation, which
is likely to induce various sorts of fragilities and inefficiencies.

: I was thinking whether we could do something like this:
: 
: class Triangle is layout<P6Hash> does autovivify{
:   method calculate_bisectors { $.bisector1 = ...;
:                                # $.bisector1 autovivifies
:                              }
: }
: 
: where it is an error without the autovivify, and only P6Hash supports 
: autovivification.

I'd just use a hash attribute.  All other things being equal, go for
simple and standard.

Larry

Reply via email to