Object::Pad review Yuki Kimoto's 2021-08-23 - Constructor argument customize
In this time, I review constructor argument customize. BUILDARGS can customize contructer argument. It is good enough for me. I think existing library that receive hash references as argument will have a slight performance penalty because a BUILDARGS function call.
Point->new($x, $y)
use strict; use warnings;use Object::Pad;
class Point {
has $x :param = 0;
has $y :param = 0;
sub BUILDARGS {
my ($class, $_x, $_y) = @_;
return (x => $_x, y => $_y);
}
method move {
my ($dX, $dY) = @_;
$x += $dX;
$y += $dY;
}
method describe {
print "A point at ($x, $y)\n";
}
}{
my $x = 5;
my $y = 10;
my $point = Point->new($x, $y);
$point->describe;
}
Point->new({x => $x, y => $y})
use strict; use warnings;use Object::Pad;
class Point {
has $x :param = 0;
has $y :param = 0;
sub BUILDARGS {
my ($class, $args) = @_;
return (%$args);
}
method move {
my ($dX, $dY) = @_;
$x += $dX;
$y += $dY;
}
method describe {
print "A point at ($x, $y)\n";
}
}{
my $x = 5;
my $y = 10;
my $point = Point->new({x => $x, y => $y});
$point->describe;
}
Leave a comment