3 ms·
Did you read the linked article? It's not the prettiest intro I've ever seen, but for perl users its benefits can be seen on http://www.houseabsolute.com/presen
by csirac2 12y ago
Did you read the linked article? It's not the prettiest intro I've ever seen, but for perl users its benefits can be seen on http://www.houseabsolute.com/presentations/intro-moose-class/#slide27 http://www.houseabsolute.com/presentations/intro-moose-class... vs http://www.houseabsolute.com/presentations/intro-moose-class/#slide28 http://www.houseabsolute.com/presentations/intro-moose-class...
Ruby code wouldn't be as verbose as this, but still once you're used to building classes with Moose accessors, types, traits etc. in a mostly declarative manner, going back to hand-rolling checks and exceptions on bad attribute values, not to mention accessor methods and so on definitely feels like a step backwards.
In fact now that I'm doing a lot of Python these days I've come to the horrible realization that it's Moose which has made me yearn for a language with stronger emphasis on typing and correctness than Python can provide!
Edit: and I don't mean "like java", where it only ever seems to get in your way...
Moose does useful things and gives you stuff "for free" once you've told it what
type something should be. And allows you trivially inherit/override type
declarations, rather than jumping through hoops as in Java.
It's a full about-face compared to the liberation I felt going from C/C++/Java to Ruby back around 2006-2007.
Slowly working through Learn you a Haskell, but doubt I'll get a chance to use Haskell professionally.
- RVuRnvbM2e 12y agoDo you mean the optional type enforcement? Admittedly it's not built-in to ruby, but it's easy to replicate.. and a lot less verbose: # Implementation: module TypedAttrs def attr_accessor_type name, type define_method name do instance_variable_get "@#{name}" end define_method "#{name}=" do |value| raise ArgumentError unless value.is_a? type instance_variable_set "@#{name}", value end end end # Example: class Foo extend TypedAttrs attr_accessor_type :bar, Integer end a = Foo.new a.bar = 5 p a.bar a.bar = "hi" # ArgumentError
- csirac2 12y agoSure. And just for attributes, there's also delegation, read-only attributes, builders, lazy init, roles, modifiers which are enforced at construction time (if `required` is true). Moose isn't hard to implement, it's actually had quite a few alternate implementations even in Perl. Python has enthought's traits package, and I've just been pointed to https://github.com/frasertweedale/elk https://github.com/frasertweedale/elk as well. BTW it sucks to nit-pick, but the Moose version isn't any more verbose than yours: package Foo; use Moose; has 'bar' => ( isa => 'Integer' );