I've seen plenty of questions and answers on whether to use getters / setters or not (such as this popular one), but I've also seen two different styles of getters / setters and very little information on which pattern is preferable and why. The first is to use 1 getter and 1 setter per class, either through named methods or using magic methods (my examples use PHP as that's what I use day to day, but my question applies to any Object Orientated Language).
<?php
class Foo {
private $bar;
private $baz;
public function get($property)
{
if (property_exists($this, $property))
return $this->$property;
}
public function set($property, $value)
{
if (property_exists($this, $property))
$this->$property = $value;
}
}
The second is to use 1 method per property
<?php
class Foo {
private $bar;
private $baz;
public function getBar()
{
return $this->bar;
}
public function setBar($value)
{
$this->bar = $value;
}
public function getBaz()
{
return $this->baz;
}
public function setBaz($value)
{
$this->baz = $value;
}
}
For the life of me I can't think of any reason to have individual methods for each property. Even if you needed individual validation you could use a switch inside one method such as:
<?php
class Foo {
private $bar;
private $baz;
public function get($property)
{
if (property_exists($this, $property))
return $this->$property;
}
public function set($property, $value)
{
if (property_exists($this, $property))
{
switch ($property)
{
case 'bar':
$this->validateBar($value);
break;
case 'baz':
$this->validateBaz($value);
break;
}
$this->$property = $value;
}
}
private function validateBar( & $value)
{
// do some validation...
}
private function validateBaz( & $value)
{
// do some validation...
}
}
Am I missing something or is there ever any need for one method per property? Is it just good practise to use one getter / setter per class?
Another option that has been brought up is the use of getsetters, a single function per property to alternatively get/set the value. I always thought this violated the single responsibility principle of SOLID, but as it's been given as an answer below I thought I would update the question to include it.