lakshmananindia has asked for the wisdom of the Perl Monks concerning the following question:

Hai I want to know what is the use of getters and setters. I faced this when I am reading Archive::Tar. I can understand the code. But I cannot relate and what is the actual use and what are the alternatives.
my $tmpl = { _data => [ ], _file => 'Unknown', }; for my $key ( keys %$tmpl ) { no strict 'refs'; *{__PACKAGE__."::$key"} = sub { my $self = shift; $self->{$key} = $_[0] if @_; return $self->{$key}; } }

Replies are listed 'Best First'.
Re: What is the use of getter and setter
by ikegami (Patriarch) on Nov 19, 2008 at 09:21 UTC
    They hide the internal structure of the object from the caller. This allows the internal structure to be changed without breaking a lot of unrelated code. This is called encapsulation.

    For example, instead of doing

    $obj->{key} = 'val';

    you'd do

    $obj->key('val');

    The latter might simply do the same thing as the former. Or maybe it adds error checking. At the very least, it gives the *option* to add error checking without breaking code.

Re: What is the use of getter and setter
by Anonymous Monk on Nov 19, 2008 at 09:17 UTC
    The comment that goes with the code says
    ### install get/set accessors for this object.
    http://en.wikipedia.org/wiki/Accessor
    In computer science, a mutator method is a method used to control changes to a variable. The mutator method, sometimes called a "setter", is most often used in object-oriented programming, in keeping with the principle of encapsulation. ... getters get values, setters set values, understand?
Re: What is the use of getter and setter
by massa (Hermit) on Nov 19, 2008 at 10:11 UTC
      if( not $node->hascode ){ $massa->msg( $node->author, "use <code> tags!!!"); $massa->satisfaction('+1'); }