moving class indepdent methods out of class definitions

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
... and into places where they can be reused by other classes,
including the possibility to 'overload' them in derived classes (not
necessarily sensible for class-independent code): Put them into a
package which exports them. Import them into the class package. That's
'roles in a nutshell' and the answer is actually so trivial (and
obvious) that I'm wondering why 'experienced perl programmers' ask
such questions.

Re: moving class indepdent methods out of class definitions

Quoted text here. Click to load it

[If you are referring to me, I have made no claims to be an experienced
Perl programmer.]

That's doable, certainly, and is indeed a simple-minded implementation
of roles. Moose roles do rather more for you than that:

    - They allow a role to require that a class consuming it implement
      certain methods. (These methods can be implemented directly or
      taken from other roles.) When combined with method modifiers this
      can be a very powerful tool for allowing hooks into a complex
      system. See Catalyst for an example.

    - They allow a class to consume a role but also to provide its own
      implementation of some of the methods provided by that role.
      Methods provided directly by the class 'hide' those imported from
      roles. Note that this does not break the role interface, since the
      method still has to be implemented somewhere.

    - The role system checks, at role-composing time, that there aren't
      any conflicts between the methods provided by the roles used by a
      given class. If there is a conflict the class needs to provide its
      own implementation of that method to make the behaviour

    - It is possible to apply one or more roles to an instance (an
      object) rather than a class. This will create a new gensymmed
      subclass of the object's current class, compose the given roles
      into that new class, and rebless the object. Again, this can be a
      very powerful way of adding new behaviour to existing objects.

You may be interested to read some of the papers by the people who
invented the concept (which they call 'traits'): .


Re: moving class indepdent methods out of class definitions


Quoted text here. Click to load it

It is a way to move class independent code out of classes into
packages which enable this code to be used as methods by any class
which provides a 'suitable interface' for accessing 'instance state'
which works with plain Perl 5. I'll mark this as a 'possibly useful
idea' for future problems but so far, I haven't missed it.

Site Timeline