在值对象中,为什么要使用特定的属性集和get方法


In a value object, why use specific property set and get methods?

在查看值对象模式时,我注意到大多数都使用单独的get和set属性函数,这两个函数编写起来都很无聊,而且会出现很多拼写错误。

有没有理由用这种风格写作,而不是通用的获取/设置例程?这是我正在使用的样板:

class ValueObject{
    protected $property1;
    protected $property2;
    protected $property3;
    public function get( $propname ){
        if( property_exists( "ValueObject", $propname ) ){
            return $this->$propname;
        }
    }
    public function set( $propname, $value ){
        if( property_exists( "ValueObject", $propname ) ){
            return( $this->$propname = $value );
        }
    }
}

getter和setter背后的想法非常有趣。

假设我们有一个用户对象,其中包含用户名、名字、姓氏和年龄,类似于

class User()
{
public $username = 'special!';
public $firstname= 'johnny';
public $lastname = 'frecko';
public $age = 55;
}

一切都很好,假设我们在$user变量中创建了一个新对象,我们可以愉快地调用$user->age来获取和设置名称。

现在,后来,出于特殊原因,您决定根据公式设置用户的年龄,该公式取决于用户本身的年龄!

在我们的小演练中,用户的年龄是他的实际年龄减去他的名字的长度!

你不能修改程序中的其他方法,它们都连接在一起,你不能在不重写所有内容的情况下创建新的实例变量,那么你该怎么办?

你从一开始就写了一个getter。类似的东西

function getAge()
{
    return $this->age;
}

写起来琐碎乏味。但现在,如果我们需要修复整个程序的年龄变量,解决方案很简单,只需向getter添加一些代码:

function getAge()
{
    return $this->age - strlen($this->firstname);
}

实际上,我们不需要重写任何东西,只需要重写这一小段代码。在你意识到自己需要getter和setter之前,你之所以要编写它们,是因为我们人类在提前计划方面很糟糕,这为你提供了一个很好的窗口,可以进一步添加一些计划外的代码。