使用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; }

而前者需要的样板代码要少得多。


当前回答

因为从现在起2周(月、年),当您意识到setter需要做的不仅仅是设置值时,您还将意识到该属性已直接用于238个其他类:-)

其他回答

在纯面向对象的世界中,getters和setters是一种可怕的反模式。阅读本文:Getters/Setters。恶毒的时期简而言之,它们鼓励程序员将对象视为数据结构,这种类型的思考是纯过程的(如COBOL或C)。在面向对象的语言中,没有数据结构,只有暴露行为的对象(不是属性/财产!)

您可以在ElegantObjects(我的面向对象编程书)的第3.5节中找到更多关于它们的信息。

根据我的经验,最好将变量设置为私有,并为每个变量提供访问器和修饰符。

通过这种方式,您可以根据需要创建只读变量,也可以只写变量。

下面的实现显示了一个只写变量。

private String foo;
public void setFoo(String foo) { this.foo = foo; }
private String getFoo() { return foo; }

下面显示了一个只读变量。

private String foo;
private void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }

到目前为止,我在回答中遗漏了一个方面,即访问规范:

对于成员,设置和获取只有一个访问规范对于setter和getter,您可以对其进行微调并单独定义

我能想到一个原因,为什么你不希望一切都公开。

例如,您从未打算在类外部使用的变量可以被访问,甚至可以通过链变量访问(即object.item.origin.x)直接访问。

通过将所有内容都设为私有,并且仅将您想要扩展的内容以及可能在子类中引用的内容设为受保护的,并且通常只将静态最终对象设为公共,那么您就可以通过使用setter和getter访问您想要的程序内容来控制其他程序员和程序可以在API中使用什么,以及它可以访问什么,以及不能访问什么,或者可能是其他恰好使用您的代码的程序员,可以在您的程序中进行修改。

如果您想要一个只读变量,但不想让客户端改变访问它的方式,请尝试使用这个模板类:

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;
};

记住,您还需要添加按位和一元运算符!这只是为了让你开始