Programming with Moose/Roles and Plugins

From Wikibooks, open books for an open world
Jump to navigation Jump to search
14:00 <@mst> EvanCarroll: add a disclaimer saying "concepts may be oversimplified and this has not been audited by the Moose developers so may not always be 
             precisely correct"
14:00 <@mst> then stevan can audit it and give a page the seal of approval if he wants to
14:00 <@mst> and not if he doesn't
14:00 < EvanCarroll> mst: sounds fair enough
14:00 <@mst> EvanCarroll: "Only a class can be subclassed, but there's no reason you can't subclass a class with a bunch of roles applied to it - also, see 
             <link to stuff on role composition>"

Qualifying scenarios for roles[edit | edit source]

Straight From The Horses Mouth
  • If you can model your problem without using Roles, and with only single inheritance do it.
  • Anything that can modeled with Roles can be modeled with Multiple Inheritance.[1]
  • If you know at compile time you want to apply a plugin, you probably don't wan't to use a plugin.[2]
  • If a plugin or role is only used one class, you're better off not using it.
  • A role should only specify methods, and not subs. Subs should be specified in a module that uses Sub::Exporter instead of Moose's role system. A role is for method composition. Roles do more than just export. SFTHM

Order sensitivity[edit | edit source]

Roles try not to be order sensitive when it comes to requirements, and conflict resolution; however, they are highly order sensitive when it comes to composition.

The order the roles are used determines the order of the method modifiers. Any method modifiers in the class before the with (keyword that includes the roles) will run before them, and any that are declared after the with will run after the roles.

Disadvantages to inheritance[edit | edit source]

  1. ^ Inheritance permits build time setting of args via the constructor, i.e, Foo->new({bar=>'baz'}). If Foo is a subclass of Bar and Bar provides a few attributes via Moose#has, those attributes can be set in Foo's constructor arguments. In the plugin model, Foo applies plugin Bar and then you only set that which Bar does via one method call per attribute, rather than by hash. There is no way to apply Bar, and then initialize Foo with Bar's modifications using one hash, nor is there a way to initialize just Bar's modifications using one hash.
    • All compile time resolution is disabled, i.e, +has => ( default => 'NewDefault' ) has no effect in a plugin.
  2. ^ You can not subclass a Role: a role for instance can provide contact information on a person, afterward it is said that a person can be contacted. A role however can not subclass that role to provide US-Specific contact information, for this you either must use two roles, or multiple-inheritance.
  3. Some tools are not supported by Roles, such as Moose's augment