NAME

Class::ActsLike - Perl extension for identifying class behavior similarities

SYNOPSIS

package HappyFunBuilding;

use Class::ActsLike qw( Bakery Arcade );

...

$building->bake( 'cookies' ) if $building->acts_like( 'Bakery' );
$building->play( 'pinball' ) if $building->acts_like( 'Arcade' );

DESCRIPTION

Polymorphism is a fundamental building block of object orientation. Any two objects that can receive the same messages with identical semantics can be substituted for each other, regardless of their internal implementations.

Much of the introductory literature explains this concept in terms of inheritance. While inheritance is one way for two different classes to provide different behavior for the same methods, it is not the only way. Perl modules such as the DBDs or Test::MockObject prove that classes do not have to inherit from a common ancestor to be polymorphically equivalent.

Class::ActsLike provides an alternative to isa().

In the example class defined above, HappyFunBuilding is marked as acting like both the Bakery and Arcade classes. It is not necessary to create an ancestor class of Building, or to have HappyFunBuilding inherit from both Bakery and Arcade. As well, one could say:

  package FauxArcade;

  use Arcade;
  use Class::ActsLike 'Arcade';

  sub new
  {
	my $class = shift;
	bless { _arcade => Arcade->new() }, $class;
  }

Provided that the FauxArcade now delegates all methods an Arcade object can receive to the contained Arcade object, this expresses the has-a relationship more accurately. Code which requires an Arcade object should, when handed an object, check to see if the object acts like an Arcade object. The FauxArcade is suitable for any sort of Hollywood production where the real Arcade is unnecessary. This is why actors always seem so good at pinball.

This technique fulfills two goals:

  • To allow you to check that the class or object you receive can handle the types of messages you're going to send it.

  • To avoid dictating how the class or object you receive handles the messages: inheritance, delegation, composition, or re-implementation.

By default, a new class automatically acts like itself, whether or not you use Class::ActsLike in its package. It also automatically acts like all of its parent classes, again without having had Class::ActsLike used in its namespace.

EXPORT

Class::ActsLike installs a new method acts_like() in the UNIVERSAL package, so it is available to all classes and objects. You may call it directly, as:

UNIVERSAL::acts_like( $class_or_object, $potentially_emulated_class );

or on a class name or object:

$class_or_object->acts_like( $potentially_emulated_class );

It returns true or false, depending on whether the class or class of the object acts like the target class.

AUTHOR

chromatic <chromatic@wgz.org>

THANKS TO

Allison Randal, for debating the theory of this idea. Dan Sugalski and Dave Rolsky for understanding the idea.

SEE ALSO

perl(1).