|laziness, impatience, and hubris|
Re: Perl OO with Class::Structby davido (Archbishop)
|on Dec 13, 2013 at 16:09 UTC||Need Help??|
I would suggest that the answer to #3 is:
Whether or not you've outgrown Class::Struct, in 2013 there is very little reason to use it. If you choose to use an OO helper (rather than writing OO by hand), and you want to stay light-weight and fast, use Moo. It's true that it is not core. But it is fast, minimal, and actively developed and used. And it's largely compatible with Moose classes.
With Moo, your example code above would look like this:
...but in this example Moo is doing more: It's assuring that the accessors "name" and "cats" can't be modified after the object has been instantiated. It's also assuring that "name" is a string.
But one real advantage is that instead of isa => ArrayRef, you could say:
Now your object instantiation verifies that all of the elements passed by Litter->new( cats => [ ... ] ) are Cats objects. You could even get more "general" by skipping the "ref $element eq 'Cat'" test, and instead allowing any sufficiently Cat-like object to pass:
With Moo you could also define a BUILDARGS subroutine that silently drops any elements from cats => [...] that don't have a "name" attribute.... if you want that behavior instead.
Now, going back to the MooX::Types::MooseLike::Base example, even these constructs are possible:
And if you want your Litter class to accept any object that has a name attribute (in other words, a litter of bobcats would be fine too, as long as they have a name attribute), you can...
Which provides clear semantics and avoids complexity. Moo makes this sort of thing pretty simple. Moose, being Moo's big uncle also has similar syntactic sugar. But Moo is so light-weight it's a great fit for small projects.
Update: So putting it all together, here's your original code with the Moo and MooX::Types::MooseLike::Base syntax:
Updated: Removed quotes from isa => checks since Moo requires a subref, and since that's what MooX::Types::MooseLike::Base provides.