Re: Magic for object constructor wanted
- From: Martijn Lievaart <m@xxxxxxxxxxxxxxxx>
- Date: Thu, 31 Jan 2008 08:39:32 +0100
On Wed, 30 Jan 2008 22:05:45 -0800, Koszalek Opalek wrote:
My code creates new objects and then populates them with data, like
this:
my $joe = Dude->new();
my $tom = Dude->new();
my $ann = Dude->new();
my $jane = Dude->new();
$joe->fill(
name => "joe",
friends => [ $ann, $tom ]
);
$jane->fill(
name => "jane",
friends => [ $ann ]
);
You will notice that the name field is always the same as the variable
that stores the object. What kind of magic would I have to use in the
constructor (or in the fill() method) so that the name of the object
does not have to be specified explicitly? In other words, I would like
to be able to say:
$joe->fill(
friends => [ $ann, tom ]
);
$jane->fill(
friends => [ $ann ]
);
and still have the name field set. This saves typing and makes sure the
variable name and the name field match.
Sure. Just don't put the objects in separate variables, put them in a
hash.
Even better, bless the hash, iow make it its own class.
Then you get something like:
use Friends;
$friends = new Friends;
$friends->add(
name => "joe",
friends => [ "ann", "tom" ]
);
$friends->add(
name => "jane",
friends => [ "ann" ]
);
Or, if these are the only options, even shorter, either:
$friends->add("joe",[ "ann", "tom" ]);
or even:
$friends->add("joe", "ann", "tom" );
The disadvantage is that you loose the compile time checking wether those
friends exist. You code will not compile if I use $anne instead of $ann,
my suggestion will compile, run and probably not even notice.
What you also can do, is store the name of the Dude in the Dude object.
This is better design anyhow, but does not save you the extra redundancy
of specifying the name twice:
my $joe = Dude->new("joe");
my $tom = Dude->new("tom");
my $ann = Dude->new("ann");
my $jane = Dude->new("jane");
$joe->add_friends($ann, $tom);
$jane->add_friends($ann);
M4
.
- Follow-Ups:
- Re: Magic for object constructor wanted
- From: Koszalek Opalek
- Re: Magic for object constructor wanted
- References:
- Magic for object constructor wanted
- From: Koszalek Opalek
- Magic for object constructor wanted
- Prev by Date: Re: Magic for object constructor wanted
- Next by Date: FAQ 1.4 What are Perl 4, Perl 5, or Perl 6?
- Previous by thread: Re: Magic for object constructor wanted
- Next by thread: Re: Magic for object constructor wanted
- Index(es):
Relevant Pages
|