![]() |
|
Perl: the Markov chain saw | |
PerlMonks |
Re^3: Class attribute handlingby tobyink (Canon) |
on Dec 12, 2019 at 23:14 UTC ( #11110043=note: print w/replies, xml ) | Need Help?? |
I do often write quite dense code, compressing a lot of ideas into just a few statenments. For example, a lot of people would do this in at least two lines of code:
Yeah, caching the hashref like you're doing is probably a good idea. A more efficient one than caching the result of mro::get_linear_isa. The disadvantage is that if _set_attr_data gets called on a class after _get_attr_data it will invalidate the cached data for that class, plus the cached data for any derived classes. I would love to sound clever and claim that's why I didn't do it that way, but honestly, I just didn't think of it! The invalidation issue can be easily solved by putting %_attr_data_cache=(); in _set_attr_data. Yes, this wipes out your whole cache whenever _set_attr_data gets called, but in most cases, your _set_attr_data calls will all happen early on, before _get_attr_data ever gets called, so it won't cause any practical slow downs.
I mean, there's certainly nothing wrong with rolling your own as a learning exercise, but the existing solutions on CPAN offer some really good and useful features, have optimized the hell out of everything, and have already thought through all the weird edge cases and gotchas. As well as Moose and Moo, consider Class::Tiny if you need a really light solution, even lighter than Moo. Moose and Moo each have a fairly interoperable syntax, though there are minor differences. Class::Tiny differs quite a lot in syntax but it interacts pretty well with Moo (and Moose? Not sure!) in terms of inheritance. You can write a base class with Class::Tiny and derived class with Moo, and things should "just work".
ref doesn't just randomly return '0' for fun sometimes, but will do so in one very specific situation: you can create a package called '0' and bless stuff into it. But I'd argue that anybody who is doing that is probably intending for you to treat their blessed references as if they were non-references. (Otherwise they'd have no reason to choose such a bizarre package name.) So for this reason, I wouldn't normally recommend checking to see if ref returned an actual 0.
In Section
Seekers of Perl Wisdom
|
|