Gist of the Day: Roles in Moose!

Have you ever struggled with how to structure your class hierarchy, given a common type of functionality which applies to some classes but not others? Say for instance you have a class named Animal. With this Animal class you can derive all of your animal classes. Take for instance a chicken, for which you subclass Animal to a class you call Chicken.
One of the features you’d like to implement is that an animal makes a noise. Chickens, for instance, cluck. Some animals, however, don’t make a noise. Take a seahorse for instance, it doesn’t make noise. It is every bit an animal, but it doesn’t make noise. There are many other mute animals across many different families of animals, so it doesn’t really seem to fit in to your hierarchy. For this purpose, you can use a Role in Moose. A role allows you to dynamically add functionality to an existing Moose class (as many of them as you like) without having to mangle your nice, clean class hierarchy. Think of it as a grab-bag of functionality for your class which can also be used by other classes regardless of their parentage.

Continue reading “Gist of the Day: Roles in Moose!”