使用getter和setter(只获取和设置)而不是简单地为这些变量使用公共字段有什么好处?
如果getter和setter所做的不仅仅是简单的get/set,我可以很快地解决这个问题,但我不是100%清楚如何做到:
public String foo;
比:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
而前者需要的样板代码要少得多。
如果您不需要任何验证,甚至不需要维护状态,即一个属性依赖于另一个属性,那么当一个属性发生更改时,我们需要维护状态。您可以通过公开字段而不使用getter和setter来保持简单。
我认为OOP会随着程序的增长而使事情变得复杂,这对于开发人员来说是一场噩梦。
一个简单的例子;我们从xml生成c++头。标头包含不需要任何验证的简单字段。但仍然像OOPS访问器一样,我们生成它们的方式如下。
const Filed& getfield() const
Field& getField()
void setfield(const Field& field){...}
这是非常冗长的并且不是必需的。一个简单的
struct
{
Field field;
};
足够且可读。函数式编程没有数据隐藏的概念,它们甚至不需要它,因为它们不会改变数据。
DataStructure和Object之间存在差异。
数据结构应该暴露其内部而不是行为。
一个物体不应该暴露其内部,但它应该暴露其行为,这也被称为德米特定律
大多数DTO被认为是一种数据结构,而不是对象。他们应该只公开自己的数据,而不是行为。在数据结构中设置Setter/Getter将暴露行为,而不是其中的数据。这进一步增加了违反德梅特定律的可能性。
鲍勃叔叔在他的《干净的代码》一书中解释了得墨忒耳定律。
有一种著名的启发式方法叫做得墨忒耳定律,它说:模块不应该知道它的对象的内部结构操纵。正如我们在上一节中看到的,对象隐藏其数据并暴露操作。这意味着对象不应公开其通过访问器的内部结构,因为这样做是为了暴露,而不是隐藏其内部结构。更准确地说,德米特定律说C类的方法f应仅调用以下方法:Cf创建的对象作为参数传递给f的对象保存在C的实例变量中的对象该方法不应在任何允许的函数返回的对象上调用方法。换句话说,与朋友交谈,而不是与陌生人交谈。
因此,根据这一点,LoD违规的例子是:
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
在这里,函数应该调用它的直接朋友的方法,这里是ctxt,它不应该调用它直接朋友的朋友的方法。但该规则不适用于数据结构。所以在这里,如果ctxt、option、scratchDir是数据结构,那么为什么要用一些行为包装它们的内部数据,并违反LoD。
相反,我们可以这样做。
final String outputDir = ctxt.options.scratchDir.absolutePath;
这满足了我们的需求,甚至没有违反LoD。
灵感来源于Robert C.Martin(Bob叔叔)的“清洁代码”
如果您想要一个只读变量,但不想让客户端改变访问它的方式,请尝试使用这个模板类:
template<typename MemberOfWhichClass, typename primative>
class ReadOnly {
friend MemberOfWhichClass;
public:
template<typename number> inline bool operator==(const number& y) const { return x == y; }
template<typename number> inline number operator+ (const number& y) const { return x + y; }
template<typename number> inline number operator- (const number& y) const { return x - y; }
template<typename number> inline number operator* (const number& y) const { return x * y; }
template<typename number> inline number operator/ (const number& y) const { return x / y; }
template<typename number> inline number operator<<(const number& y) const { return x << y; }
template<typename number> inline number operator^(const number& y) const { return x^y; }
template<typename number> inline number operator~() const { return ~x; }
template<typename number> inline operator number() const { return x; }
protected:
template<typename number> inline number operator= (const number& y) { return x = y; }
template<typename number> inline number operator+=(const number& y) { return x += y; }
template<typename number> inline number operator-=(const number& y) { return x -= y; }
template<typename number> inline number operator*=(const number& y) { return x *= y; }
template<typename number> inline number operator/=(const number& y) { return x /= y; }
primative x;
};
示例用途:
class Foo {
public:
ReadOnly<Foo, int> cantChangeMe;
};
记住,您还需要添加按位和一元运算符!这只是为了让你开始