使用Accessors满足
Uniform Access Principle.
引用维基百科:
The Uniform Access Principle was put forth by Bertrand Meyer. It states “All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.” This principle applies generally to object-oriented programming languages. In simpler form, it states that there should be no difference between working with an attribute, precomputed property, or method/query.
It effectively means that a client of the person should neither know nor care whether the age is stored or computed. This gives the person object the flexibility to change between the two easily as well as removing what is usually an unnecessary concern from the client. It’s an important part of encapsulation – or at least the data-hiding aspect of encapsulation.
为了说明这一点,想象一下这样的一个类:
class Now
{
public $timestamp;
public function getTomorrow()
{
return strtotime('+1 day', $this->timestamp);
}
// … more code
当您这样做时,您正在强制开发人员使用该类来了解实现细节.要获得现在的时间戳,开发人员必须这样做
echo $now->timestamp;
而要获得明天的计算时间戳,开发人员必须这样做
echo $now->getTomorrow();
但开发人员不需要关心,因此如果您想要遵循UAP,您将提供一个Accessor来获取时间戳.并通过方法汇集所有访问权限.
这样做还具有更稳定的API的额外好处.想象一下,您需要在项目的后期更改实现细节,并将时间戳转换为DateTime对象.你的班级现在看起来像这样:
class Now
{
public $dateTime; //
public function getTomorrow()
{
return strtotime('+1 day', $this->dateTime->getTimestamp());
}
// … more code
现在,任何以前使用过$now-> timestamp的开发人员都必须更改其消费代码以适应该更改.虽然从一开始就使用了Getter,但它根本不是问题,因为Getter会确保它返回时间戳.为了进一步证明这一点,请注意开发人员如何不必更改任何内容以使用getTomorrow().虽然在内部我们更改了细节,但公共API的行为仍然相同.
请注意,UAP只是一个指导原则.现代IDE使您可以轻松地为您生成Accessors和Mutators,因此很容易理解.但这不是绝对的事实.如果您可以合理地证明不遵守它,那么请不要遵循它并使用公共属性.但它应该是一个明智的决定.
但是,总的来说,you want to avoid Getters(和Setters)无论如何都是just tell your objects what to do.这将给出一个更加纤薄的API.如果您的API有很多很多Getters,那么您很可能会将对象内部的代码分散到消费者中.