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

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


当前回答

考虑使用访问器是有充分理由的,因为没有属性继承。请参见下一个示例:

public class TestPropertyOverride {
    public static class A {
        public int i = 0;

        public void add() {
            i++;
        }

        public int getI() {
            return i;
        }
    }

    public static class B extends A {
        public int i = 2;

        @Override
        public void add() {
            i = i + 2;
        }

        @Override
        public int getI() {
            return i;
        }
    }

    public static void main(String[] args) {
        A a = new B();
        System.out.println(a.i);
        a.add();
        System.out.println(a.i);
        System.out.println(a.getI());
    }
}

输出:

0
0
4

其他回答

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

例如,您从未打算在类外部使用的变量可以被访问,甚至可以通过链变量访问(即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;
};

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

如果您不需要任何验证,甚至不需要维护状态,即一个属性依赖于另一个属性,那么当一个属性发生更改时,我们需要维护状态。您可以通过公开字段而不使用getter和setter来保持简单。

我认为OOP会随着程序的增长而使事情变得复杂,这对于开发人员来说是一场噩梦。

一个简单的例子;我们从xml生成c++头。标头包含不需要任何验证的简单字段。但仍然像OOPS访问器一样,我们生成它们的方式如下。

const Filed& getfield() const
Field& getField() 
void setfield(const Field& field){...} 

这是非常冗长的并且不是必需的。一个简单的

struct 
{
   Field field;
};

足够且可读。函数式编程没有数据隐藏的概念,它们甚至不需要它,因为它们不会改变数据。

事实上,考虑使用访问器而不是直接公开类的字段有很多很好的理由——不仅仅是封装和使未来的更改更容易。

以下是我知道的一些原因:

与获取或设置属性相关的行为的封装-这允许以后更容易地添加附加功能(如验证)。隐藏属性的内部表示形式,同时使用替代表示形式公开属性。隔离您的公共接口不受更改的影响——允许公共接口在实现更改时保持不变,而不影响现有用户。控制属性的生存期和内存管理(处置)语义——在非托管内存环境(如C++或Objective-C)中尤为重要。在运行时为属性更改时提供调试拦截点-在某些语言中,如果没有此功能,则很难调试属性更改为特定值的时间和位置。改进了与旨在针对属性getter/setter进行操作的库的互操作性——Mocking、Serialization和WPF应运而生。允许继承者通过重写getter/setter方法来更改属性的行为和公开方式的语义。允许getter/setter作为lambda表达式而不是值传递。获取器和设置器可以允许不同的访问级别-例如,获取可以是公共的,但集合可以受到保护。

取决于你的语言。您已经将其标记为“面向对象”而不是“Java”,因此我想指出ChssPly76的答案依赖于语言。例如,在Python中,没有理由使用getter和setter。如果需要更改行为,可以使用一个属性,该属性将getter和setter包装在基本属性访问周围。类似于:

 class Simple(object):
   def _get_value(self):
       return self._value -1

   def _set_value(self, new_value):
       self._value = new_value + 1

   def _del_value(self):
       self.old_values.append(self._value)
       del self._value

   value = property(_get_value, _set_value, _del_value)