On the Subject of Objects

From JmPm

Revision as of 12:51, 7 December 2008 by Rina (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search



Object orientation

 Some basic oops concepts

 blessed objects

 inheritance

 polymorphism

 encapsulation

 persistence

 methods


 @ISA

 constructors

 Diamonds-multiple inheritance

 can()

 isa()




 derived classes

 empty subclass test

 abstract methods


 Our @ISA qw(whatever);

 Parents

 Left-right, down-up

 Use base (prefered) –which is:

require Foo; 
require Bar; 
push @ISA, qw(Foo Bar);

But .. Cannot change @ISA , packages may not be in single unique .pm

Perhaps we do not need inheritance at all ?


 2 argument bless

 Generalized “new” can then call the blessed class to fill attributes

Sub new{
My ($class,%args)=@_;
My $self =bless{}, ref($class)||$class;
$self-> _init(%args);
Return $self;


 test for multiple inheritance

Sub _init{
My ($self,%args)=@_;
Return if $self->{_init}{__PACKAGE__}++
Do other init things

This will work also for destructors or any other module that you do not want to do more than once

 Loop through all of the parents

Sub somesub{
Foreach my $parent(@ISA){
  my $ancestor_sub=$parent->can(“somesub”);
  $self-> $ancestor_sub() if $ancestor_sub;

$self->$_for (map{$_->can(“somesub”)||()} @ISA);


 Checks through all @ISA inheritance

 Returns reference to method that can be called

My $method_call=$obj->can(“do1”)
 || =$obj->can(“do2”) || =$obj->can(“do3”) ;
Return $obj ->$method_call() if $method_call;


 Checks if the named method is an ancestor of the current method


 The base class from which all classes are derived-looks here after @ISA

 Can put a general method in UNIVERSAL

 isa() and can() are here

Sub UNIVERSAL::_debug{
 ..do debug here…


 Method AUTOLOAD can be anywhere in the hierarchy

 If a method is not found and there is an AUTOLOAD, it is executed

 $AUTOLOAD=the full method name of what was not found

 For long seldom used subroutines



 Looks for method in the parent of the current class – not the parent of the invoking object

 Uses same search as usual in @ISA etc.

derived classes

 Care must be taken not to mix up variable names of inherited data

 Use prefix of class name

 empty subclass test

 Call a method from an empty child method and see if it is found

 abstract methods

 Placeholder in the parent class that throws and exception, insuring that all of the children have that same named method


 Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway

 Learning Perl Objects, References, and Modules by Randal L. Schwartz and Tom Phoenix

 Advanced Perl Programming by Simon Cozens

 Programming Perl (3rd Edition) by Larry Wall, Tom Christiansen, and Jon Orwant

 Perl Best Practices by Damian Conway

Personal tools