I've been writing the Moose section of the Modern Perl book for the past week. Stevan (and other people) suggested that I explain how to create and use objects in Perl with Moose before explaining the bare-bones blessed reference approach. They were right.

I'm assuming that readers don't necessarily have the theoretical understanding of how objects work and why, of why Liskov substitutability is important, of what allomorphism means, and why polymorphism and encapsulation are much more interesting than inheritance. I don't even assume that readers know any of those words.

Yet I've noticed something far more interesting.

The standard approach to teaching Perl 5 OO (at least, the one approach I've seen that works) builds on the Perl 5 implementation ideas. That is to say, "a class is a package, a method is a subroutine, and an object is a blessed reference". If you know how to work with references in Perl 5, you can use Perl 5 objects.

That's true in the sense that a blessed hash reference is still a hash reference. That's false in the sense that treating an object as a struct with a vtable pointer is a terrible way to write robust OO. (I should know; I've been hip deep in multiple implementations.)

I like a lot of things about Moose, but what I appreciate most from a didactic standpoint is that I can explain object attributes:

{ package Cat; use Moose; has 'name', is => 'ro', isa => 'Str'; has 'diet', is => 'rw', isa => 'Str'; has 'birth_year', is => 'ro', isa => 'Int', default => (localtime)[5] + 1900; }

... and it doesn't occur to readers that they can poke into a Cat instance directly (even though they can). Moose encourages people to do the right thing by using accessors and respecting encapsulation and polymorphism and allomorphism and substitution by making something different--encapsulated access to instance data--look different from the well-understood mechanism of its implementation.

Objects may still be blessed hashes, but users treat them differently because they have different expectations.

In writing the examples for this chapter, I changed the implementation of the class to make correctness easier (and to discuss the value of immutable objects). The refactoring was trivial, thanks to Moose features, but the interface of the class could stay the same, thanks to Moose's subtle encouragement to program to an encapsulated interface.

I always enjoy encountering such a serendipity in code, and I made sure to mention it in the book. The Perl world needs more such serendipities.