Most tutorials that teach Perl OOP (Object Oriented Programming) focus on the nuts and bolts (which is important), but neglect the equally important "Why" or reasons for using OOP. This is an attempt to remedy that, in the form of a story.
A fable
There once was a farmer who had a flock of sheep. His typical workday looked like this:Eventually, due to successful wool sales, he expanded his farming activities and his day become like this:$farmer->move_flock($pasture); $farmer->monitor_flock(); $farmer->move_flock($home);
But now the farmer wanted to devote more time to other_important_work(), so he decided to hire a minion to handle the sheep related work, so the work was now split like this:$farmer->move_flock($pasture); $farmer->monitor_flock(); $farmer->move_flock($home); $farmer->other_important_work();
This did give the farmer more time for other_important_work(), but unfortunately $shepherd_boy had a tendency to cry wolf so the farmer had to replace him with a new minion:$shepherd_boy->move_flock($pasture); $shepherd_boy->monitor_flock(); $shepherd_boy->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.$sheep_dog->move_flock($pasture); $sheep_dog->monitor_flock(); $sheep_dog->move_flock($home); $farmer->other_important_work();
Ideas
Delegation
To handle complexity, delegate to a suitable entity e.g. the farmer delegates some of his work to $shepherd_boy.Encapsulation
Tell objects what to do, rather than micro-manage e.g.rather than$sheep_dog->monitor_flock();
At a high level, we do not particularly care what the internals of the object are. We only care what the object can do.$sheep_dog->{brain}{task}{monitor_flock} = 1;
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.I've had this in my scratchpad for a long time and I'm sure there's more that can be said, but I finally decided to post this after reading OOP's setter/getter method - is there a way to avoid them? in case anyone finds it helpful.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: OOP: A Bird's Eye View
by Laurent_R (Canon) on Oct 29, 2015 at 17:06 UTC | |
by Arunbear (Prior) on Oct 30, 2015 at 11:02 UTC | |
by Laurent_R (Canon) on Oct 30, 2015 at 12:52 UTC | |
Re: OOP: A Bird's Eye View
by tiny_monk (Sexton) on Oct 28, 2015 at 08:30 UTC | |
Re: OOP: A Bird's Eye View
by TGI (Parson) on Dec 30, 2015 at 02:00 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. |
Back to
Meditations