Main Content

Using object orientation for non-physical objects

Archive - Originally posted on "The Horse's Mouth" - 2013-05-22 22:11:50 - Graham Ellis

A table, a flower, a dog, a train and the second hand on a clock are all physical objects. And when teaching people about Object Oriented programming, using such things as examples is a real help in getting the concepts across an showing how they're implemented. But objects to further than that too - to allow you to represent other "virtual" things too. You'll often find objects which are FTP connections, file handles, regular expressions, and so on. And you'll find objects going even further sometimes too - it's an excellent model to use where you need to make some settings and then keep applying algorithms too.

Two excellent examples came up on the Perl for Larger Projects course that finished today - let me share them with you to help explain why, and how, objects are used in this non-physical way.

a) I want to send a response from a program to lots of people - each response personalised with a set of values but in a common shell. So I construct a "Template" object, then pass into it a set of key, value pairs which will fill in a copy of the template and return that completed text to me. The whole business of how to fill in the template is encapsulated in the class, and by using an object I can be efficient in reading in the template just once, and easily expand my program later to make use of multiple templates.

Loading the template:
  $emailFrame = new Template("message.htp");
and filling it in:
  %stuffing = (bob => "'Enry",
    lots => 27,
    coboss => "Earl Wantland"
    );
  $toSend = $emailFrame->fillIn(\%stuffing);


Complete source code [here] showing a none-OO (and non-expandable, code all mixed in) example, and [here] showing the code refactored to an expandable and easier to manage OO approach. Sample data [here].


b) When writing a function, I want to be able to check my user's input parameters and warn or exit gracefully if the call is in error. Rather than rewrite lots of testing code, I started to formulate a validation object.

Here's an example of the use of the class... set up to check that we have two integer parameters:
  $addval = new Validate(["i","i"]);
Make the actual checks:
  $addval->checkToDie(@_);

The separation of the setup into the constructor and checking itself in a separate object method allows me to share a single check object (which may have an element of setup time involved in initial interpretation) between many requirements to make checks, and between a series of methods such as checkToDie, checkToWarn and checkToLog.

Source code of a piece of code that uses the class [here] and the class definition [here].