9.13 Getters That Double as Setters

Another alternative to the pattern of creating two different methods for getting and setting a parameter is to create one method that notes whether or not it gets any additional arguments. If the arguments are absent, it's a get operation; if the arguments are present, it's a set operation. A simple version looks like:

sub color {
  my $shift;
  if (@_) {              # are there any more parameters?
    # yes, it's a setter:
    $self->{Color} = shift;
  } else {
    # no, it's a getter:

Now you can say:

my $tv_horse = Horse->named("Mr. Ed");
print $tv_horse->name, " is colored ", $tv_horse->color, "\n";

The presence of the parameter in the second line denotes that you are setting the color, while its absence in the third line indicates a getter.

While this strategy might at first seem attractive because of its apparent simplicity, it complicates the actions of the getter (which will be called frequently). This strategy also makes it difficult to search through your listings to find only the setters of a particular parameter, which are often more important than the getters. In fact, we've been burned by this in the past when a setter became a getter because another function returned more parameters than expected after an upgrade.