http://qs321.pair.com?node_id=1146127


in reply to Re^4: OOP's setter/getter method - is there a way to avoid them?
in thread OOP's setter/getter method - is there a way to avoid them?

Not all objects need setter methods. Not all values associated with an object with setters needs its own setter. The getter/setter pair is for things that are both to be accessed by other code outside your object and mutable (that is, updatable) outside the object or from elsewhere in the object.

If you want an immutable value within your object, you don't have to provide a setter. This won't enforce encapsulation by itself, but it makes it apparent that there's an intent that the value not be updated. Actual enforcement of data hiding is a separate topic.

If some piece of data should remain entirely private to your object or to the class, then there's no need to create a getter for it, either.

As for encapsulation within the object, yes it's important that if you have a getter or setter that it retrieves or updates the data in the data structure itself. However, there is some convincing argument on either side of the issue of whether one value's setter and getter should ever access another value within the object directly even within the same object. Some people say direct access to another value in the same object is fine. Others recommend that any part of the object that isn't value B's getter or setter use those methods to access value B.

Maybe you have a fruit that changes color as it ripens, but it's never going to change what kind of fruit it is.:

use strict; use warnings; package Fruit; sub new { my $class = shift; my $self = { name => shift, color => shift }; bless $self, $class; }; sub get_color { return $_[0]->{ 'color' }; } sub set_color { $_[0]->{ 'color' } = pop; } sub get_name { return $_[0]->{ 'name' }; } package main; my $obj = Fruit->new( 'apple', 'red' ); my $obj2 = Fruit->new( 'banana', 'green' ); $obj2->set_color( 'yellow' ); use Data::Dumper; print Dumper( $obj, $obj2 ); for my $fruit ( $obj, $obj2 ) { printf "The %s is %s\n", $fruit->get_name, $fruit->get_color; }