perlmeditation
RonW
<p>Ovid's [id://1220917] got me curious, so I did some searching and found something interesting.</p>
<p>Object creation in Perl compared to Smalltalk (the putative parent language of OO languages): They are surprisingly similar.</p>
<p>Using Ovid's Point example, in Smalltalk:</p>
<c>
Object subclass: 'Point' instanceVariables: 'x y '
x
^x
x: coord
x := coord
y
^y
y: coord
y := coord
init
x := Float new.
y := Float new.
</c>
<p>Then to create an instance:</p>
<c>
p := Point new.
p init.
p x: 1.5.
p y: 1.5.
</c>
<p>Doesn't that look a lot like:</p>
<c>
my $p = bless {}, Point;
$p->init;
$p->x(1.5);
$p->y(1.5);
</c>
<p>For a friendlier object creation, you can define a class method to do all that:</p>
<c>
newX: xc Y: yc
p := Point new.
p init.
p x: xc.
p y: yc.
^p
</c>
<p>Then:</p>
<c>
Point newX: 1.5 Y: 1.5.
</c>
<p>Also, Smalltalk's <c>new</c> is a method inherited from the Object class and can be overridden by defining a <c>new</c> method as a class method of any user defined class. I'm leaving that as exercise for the readers.</p>
<p>So, maybe Perl 5's much maligned OO system can be blamed on Smalltalk. Not sure what else Larry et al had available to look at, but looks like Smalltalk had a strong influence.</p>
<p>Still, there is hope for Perl 5's OO system.</p>
<p>For those who've forgotten or are not familiar, Perl 5 has an equivalent to Object called UNIVERSAL. All classes in Perl 5 inherit from UNIVERSAL.</p>
<p>In theory, Perl 5 could provide a default <c>new</c> method for all classes by defining a <c>new</c> method in UNIVERSAL.pm</p>
<p>Maybe Ovid can present a compelling enough argument to do that. That would be a great first step.</p>
<p>But, since I'm writing this comment, I'll suggest 2 additions to UNIVERSAL.pm</p>
<c>
sub init
{
# Nothing to do, this is just here so classes don't have to define init
}
sub new
{
my $class = shift;
my $object = bless {}, $class;
$object->init(@_);
return $object;
}
</c>
<p>I'm sure someone will come up with a better default <c>new</c>. This one is just an example of what could be done.</p>
<p>Disclaimer: None of this code is tested. YMMV</p>