The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

An OOP Tutorial

A Bird's Eye View of OOP

The following fable illustrates the main ideas of OOP.

There once was a farmer who had a flock of sheep. His typical workday looked like:

    $farmer->move_flock($pasture)
    $farmer->monitor_flock()
    $farmer->move_flock($home)

    $farmer->other_important_work()

In order to devote more time to other_important_work(), the farmer decided to hire a minion, so the work was now split like this:

    $shepherd_boy->move_flock($pasture)
    $shepherd_boy->monitor_flock()
    $shepherd_boy->move_flock($home)

    $farmer->other_important_work()

This did give the farmer more time for other_important_work(), but unfornately $shepherd_boy had a tendency to cry wolf so the farmer had to replace him:

    $sheep_dog->move_flock($pasture)
    $sheep_dog->monitor_flock()
    $sheep_dog->move_flock($home)

    $farmer->other_important_work()

$sheep_dog was more reliable and demanded less pay than $shepherd_boy, so this was a win for the farmer.

Ideas

Object Oriented design is essentially the act of minionization, i.e. deciding which minions (objects) will do what work, and how to communicate with them (using a special set of messages known as an interface).

The most important ideas are

Delegation

To handle complexity, delegate to a suitable entity e.g. the farmer delegates some of his work to $shepherd_boy (and later on to $sheep_dog).

Encapsulation

We tell objects what to do, rather than micro-manage e.g.

    $sheep_dog->monitor_flock();

rather than

    $sheep_dog->{brain}{task}{monitor_flock} = 1;

At a high level, we do not particularly care what the internals of the object are. We only care what the object can do.

But, an object becomes harder to change the more its internals are exposed.

Polymorphism

$sheep_dog and $shepherd_boy both understood the same commands, so replacing the latter with the former was easier than it would have been otherwise.