Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2006 > March
SysAdminMag.com

Inside-Out Objects

Randal L. Schwartz

In my previous article, "Generating Object Accessors", which appeared in the January 2006 issue, I created a traditional hash-based Perl object: a Rectangle with two attributes (width and height) using the constructor and accessors like so:

package Rectangle;
sub new {
  my $class = shift;
  my %args = @_;
  my $self = {
    width => $args{width} || 0;
    height => $args{height} || 0;
  };
  return bless $self, $class;
}
sub width {
  my $self = shift;
  return $self->{width};
}
sub set_width {
  my $self = shift;
  $self->{width} = shift;
}
sub height {
  my $self = shift;
  return $self->{height};
}
sub set_height {
  my $self = shift;
  $self->{height} = shift;
}
I can construct a 3-by-4 rectangle easily:

my $r = Rectangle->new(width => 3, height => 4);
At this point, $r is an object of type Rectangle, but it's also simply a hashref. For example, the code in set_width merely deferences a value like $r to gain access to the hash element with a key of width. But does Perl require such code to be located within the Rectangle package? No. As a user of the Rectangle class, I could easily say:

$r->{width} = 5;
and update the width from 3 to 5. This is "peering inside the box" and will lead to fragile code, because we've now exposed the implementation of the object, not just the interface.

For example, suppose we modify the set_width method to ensure that the width is never negative:

use Carp qw(croak);
sub set_width {
  my $self = shift;
  my $width = shift;
  croak "$self: width cannot be negative: $width"
    if $width < 0;
  $self->{width} = $width;
}
If the $width is less than 0, we croak, triggering a fatal exception, but blaming the caller of this method.



MarketPlace

Free Download Speeds Up PCs
Make Your PC Faster --New Diskeeper 2008 Speeds Up PCs --Download Free Trial Now!

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

Flowcharts from C/C++ code -- Free trial download
Understand C/C++ code in less time. A new team member ? Inherited legacy code ? Get up to speed faster with Crystal Flow for C/C++. Code-formatting improves readability. Flowcharts are integrated with code browser. Export flowcharts to Visio.

WinDev 12 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?