|XP is just a number|
Moose: What about "class" attributes?by John M. Dlugosz (Monsignor)
|on Apr 30, 2011 at 08:37 UTC||Need Help??|
John M. Dlugosz has asked for the
wisdom of the Perl Monks concerning the following question:
I was under the impression that Moose did not have "class attributes", by which I mean a slot that is associated with all instances of a type rather than being per-instance. In C++ this would be a static member. In Smalltalk I think it's called a class variable.
I looked at Moose Manual Attributes to be sure, and it states, "An attribute is a property that every member of a class has."
Why the double-take? Because I see MooseX::Traits adds an attribute to the class called _trait_namespace whose value is used when you write:
How can Class->with_traits use a value found in a property of some specific instance of Class when it is not called on any instance? It sure looks like it must be a class variable!
The instructions on overriding the value of _trait_namespace does not show anything different. So what's going on here?
I want to do something similar, and have a value that is used by some class method (like new) and can be changed by a derived class. This looks like the accessor is a virtual class method (something C++ doesn't have).
In Smalltalk, class slots and virtual class methods are simply normal slots and methods on the metaclass instance (the class object itself). So it makes sense that Moose should accommodate such a thing as it uses the same architecture.
Looking at the source of MooseX::Traits, I see a perfectly ordinary has in a role. However, it is 'bare', so there is no getter and nothing else that would make it usable. Eventually, there is a call to
So, I guess it's a hack. The slot is never used in an instance, and the default is accessed without any instance being populated with it. (Edit: Worse, I see that if the default is a sub ref, it is called with no arguments at all. The default sub is documented as being called as a method on the object. )
The use of such a thing is testimony that "class variables" and "class methods" are indeed wanted!