in reply to Convenient Constructors - a Moo question

This seems like an example of where subclasses and polymorphism actually make sense.

use Attack::Heavy; use Attack::Lite; use Attack::Fast; my @attacks = ( Attack::Heavy->new, Attack::Lite->new, Attack::Fast->new, );

If you prefer, internally "Attack" could be a role that defines a common interface, and "Attack::Heavy", "Attack::Lite", and "Attack::Fast" could be composed with that role. Or inheritance could be used, whichever is your preference. Actually, inheritance is probably preferable here, because there are probably times where you would just instantiate an Attack object without using the defaults provided by ::Heavy, ::Lite, and ::Fast.

This is classic Perl-style object polymorphism; As long as an object can 'type', 'damage', and 'speed', it's sufficiently Attack like to be treated like an Attack object.


Dave

Replies are listed 'Best First'.
Re^2: Convenient Constructors - a Moo question
by blindluke (Hermit) on Dec 06, 2014 at 20:02 UTC

    Thank you for the reply, but I cannot agree with you on this one. Subclassing would be useful if the new classes would add anything to the base class. It seems completely unnecessary here, when the only difference between a Heavy Attack and a Light Attack is the set of attribute values.

    The association between seeing subtypes of anything and thinking about inheritance as a possible solution is a natural one, but it's not always a good thing. It even has it's own section in Ovid's excellent Often Overlooked OO Programming Guidelines. To quote the first couple of sentences in "Don't subclass simply to alter data":

    Subclass when you need a more specific instance of a class, not just to change data. If you do that, you simply want an instance of the object, not a new class. Subclass to alter or add behavior.

    - Luke

      Eh... I have to admit that within a few minutes of making my post I wasn't so convinced either. ;)


      Dave