|There's more than one way to do things|
Re^2: Moose - my new religionby tobyink (Abbot)
|on Jan 08, 2012 at 12:49 UTC||Need Help??|
Assuming you already use OO, Moose makes a lot of common tasks much easier. Writing object accessors (i.e. getter/setter methods) all the time gets tedious. Moose makes them trivial - and even adds type checking. So if your BankAccount class has a "current_balance" attribute, rather than writing something like this:
You just write this:
And as a bonus, you get the same type checking thrown in to your constructor. (And you never need to write sa constructor again!)
It frees you from having to worry about the ins and outs of writing constructors and accessors and so on, allowing you to spend more time focussed on higher level stuff. That's got to be a good thing.
Method modifiers are another great thing. Say you have a class DB which offers methods "select", "insert", "update" and "delete". For debugging you might want to create this class:
That way, whenever one of those methods is called, you see a warning about it. But for this to work, you'd need to go through your code and replace DB->new with DebuggingDB->new everywhere. But we can go better than that...
Now DebuggingDB is not a class, but a role, and we can compose it at run-time:
But maybe we know the connection to the accounts database is working fine, and we only need to debug the connection to marketing...
The ability to apply roles not just to classes, but to objects at run-time, is very powerful. This is something you can do without Moose, certainly, but Moose makes it a lot easier.
Lastly, it gives you some very powerful introspection: much more so than Perl's default OO introspection (isa, can and DOES).
Yes, Moose does have a performance hit. However, much of that is compile-time rather than run-time. So if you have a long-running process, such as a daemon, this is usually quite acceptable. (Whereas in a CGI script, where start-up time is important, Moose would probably be impractical.)
Moose isn't right for every project, but if you're doing OO, if start-up time isn't so important, and you don't care about adding some pretty heavy dependencies to your project, then it's a natural choice.