Managing Instance Data

Problem

Each data attribute of an object, sometimes called data members or properties, needs its own method for access. How do you write these functions to manipulate the object’s instance data?

Solution

Either write pairs of get and set methods that affect the appropriate key in the object hash, like this:

sub get_name {
    my $self = shift;
    return $self->{NAME};
} 

sub set_name {
    my $self      = shift;
    $self->{NAME} = shift;
}

Or, make single methods that do both jobs depending on whether they’re passed an argument:

sub name {
    my $self = shift;
    if (@_) { $self->{NAME} = shift } 
    return $self->{NAME};
}

Sometimes, it’s useful to return the previous value when setting a new value:

sub age {
    my $self = shift;
    my $prev = $self->{AGE};
    if (@_) { $self->{AGE} = shift } 
    return $prev;
} 
# sample call of get and set: happy birthday!
$obj->age( 1 + $obj->age );

Discussion

Methods are how you implement the public interface to the object. A proper class doesn’t encourage anyone to poke around inside its innards. Each data attribute should have a method to update it, retrieve it, or both. If a user writes code like this:

$him = Person->new();
$him->{NAME} = "Sylvester";
$him->{AGE}  = 23;

then they have violated the interface, so deserve whatever they get.

For nominally private data elements, you may omit methods that access them.

By mandating a strictly functional interface, you are free to alter your internal representation later without fear of breaking code. The functional interface ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.