Tuesday, 17 January 2012

OOPerl Basics

Thanks to Perl Cookbook  writers for wisdom sharing:

If you ask ten people what object orientation is, you'll get ten different answers. People bandy about terms like abstraction and encapsulation, trying to isolate the basic units of object-oriented programming languages and give them big names to write papers and books about. Not all object-oriented languages offer the same features, yet they are still deemed object-oriented. This, of course, produces more papers and books.
We'll follow the nomenclature used in Perl's documentation, the perlobj (1) manpage, and Chapter 5 of Programming Perl , "Libraries, Modules, and Classes." An object is a variable that belongs to a class . Methods are functions associated with a class or object. In Perl, a class is a package  - and usually a module. An object is a reference to something that's been blessed into a class. Blessing associates a referent with a class. This is done with the bless function, which takes one or two arguments. The first is a reference to the thing to bless, and the optional second argument is the package to bless it into.
$object = {};                       # hash reference
bless($object, "Data::Encoder");    # bless $object into Data::Encoder class
bless($object);                     # bless $object into current package
The class name is the package name ( Data::Encoder in the example above). Because classes are modules (usually), the code for the Data::Encoder class resides in the file Data/Encoder.pm . As with traditional modules, the directory structure is purely for convenience; it implies nothing about inheritance, variable sharing, or anything else. Unlike a traditional module, though, an object module seldom if ever uses the Exporter. Access should be through method calls only, not imported functions or variables.
Once an object has been blessed, calling the ref function on its reference returns the name of its class instead of the fundamental type of referent:
$obj = [3,5];
print ref($obj), " ", $obj->[1], "\n";
bless($obj, "Human::Cannibal");
print ref($obj), " ", $obj->[1], "\n";


Human::Cannibal 5
As you can see, you can still dereference a reference once it has been blessed. Most frequently, objects are implemented as blessed hash references. You may use any kind of reference you want, but hash references are the most flexible. They let you have arbitrarily named data fields in an object.
$obj->{Stomach} = "Empty";   # directly accessing an object's contents
$obj->{NAME}    = "Thag";        # uppercase field name to make it stand out (optional)
Although Perl permits it, it's considered poor form for any code outside the class to directly access the contents of an object. The point of objects, everyone agrees, is to give you a nominally opaque handle to something that you access through designated methods only. This lets the maintainer of the class change its implementation without needing to change all application code that uses the class.


To call a method, use -> . Here, we call the encode() method of $object with the argument "data" and store the return value in $encoded :
$encoded = $object->encode("data");
This is an object method , because we call the method on an object. We can also have class methods , methods called on class names.
$encoded = Data::Encoder->encode("data");
Invoking a method calls the function in the corresponding class, implicitly passing as the initial argument either a reference for object methods or a string for class methods. Recipe 13.7 shows how to make method calls where the method is determined at runtime.
Most classes provide constructor methods, which return new objects. Unlike some object-oriented languages, constructor methods in Perl are not specially named. In fact, you can name them anything you like. C++ programmers have a penchant for calling their constructors in Perl new . We recommend that you name your constructors whatever makes sense in the context of the problem you're solving. For example, constructors in the Tk extension to Perl are named after the widgets they create. A less common approach is to export a function with the same name as the class; see "Example: Overloaded StrNum Class " in Recipe 13.14 for an example.
A typical constructor looks like this:
sub new {
    my $class = shift;
    my $self  = {};         # allocate new hash for object
    bless($self, $class);
    return $self;
Call the constructor with:
$object = Class->new();
If there isn't any inheritance or other monkey business working behind the scenes, this is effectively the same as:
$object = Class::new("Class");
The new() function's first argument here is the class name to bless the new reference into. A constructor should pass that string as the second argument to bless() .
Recipe 13.1 also talks about functions that return blessed references. Constructors don't have to be class methods, and writing object methods that return new objects have a number of uses, as discussed in Recipe 13.6 .
A destructor is a subroutine that runs when an object's referent is garbage collected. Unlike constructors, you have no choice in naming it. You must name your destructor method DESTROY . This method, if it exists, will be called for all objects immediately prior to memory deallocation. Destructors, described in Recipe 13.2 , are optional.
Some languages syntactically allow the compiler to restrict access to a class's methods. Perl does not  - it allows code to call any method of an object. The author of a class should document clearly the public methods (those which may be used), and the user of a class should avoid undocumented (implicitly private ) methods.

For more:

No comments:

Post a Comment

Tweets by @sriramperumalla