为什么要使用getter和setter / accessors? [英] Why use getters and setters/accessors?
问题描述
使用getter和setter有什么好处 - 只能获取和设置 - 而不是简单地为这些变量使用公共字段?
What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?
如果getter和setter一直在做不仅仅是简单的获取/设置,我可以非常快地计算出这个,但我不是100%明确如何:
If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:
public String foo;
更糟糕的是:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
前者需要更少的样板代码。
Whereas the former takes a lot less boilerplate code.
推荐答案
实际上有许多好的理由考虑使用访问者而不是直接暴露类的字段 - 超出了封装的论点和使未来的变化更容易。
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
以下是我所知道的一些原因:
- 封装与获取或设置属性相关的行为 - 这样可以在以后更轻松地添加其他功能(如验证)。
- 隐藏属性的内部表示形式使用替代表示公开属性时。
- 保护公共接口免受更改 - 允许公共接口在实现更改时保持不变,而不会影响现有使用者。
- 控制属性的生命周期和内存管理(处理)语义 - 在非托管内存环境(如C ++或Objective-C)中尤为重要。
- 提供调试拦截指向属性在运行时更改的时间 - 在某些语言中调试属性更改为特定值的时间和位置可能非常困难。
- 已改进设计用于对属性getter / setter进行操作的库的互操作性 - 脑海中浮现出模拟,序列化和WPF。
- 允许继承者更改属性的行为和暴露的语义覆盖getter / setter方法。
- 允许getter / setter作为lambda表达式而不是值传递。
- getter和setter可以允许不同的访问级别 - 例如,获取可能是公共的,但该组可能受到保护。
- Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
- Hiding the internal representation of the property while exposing a property using an alternative representation.
- Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
- Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
- Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
- Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
- Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
- Allowing the getter/setter to be passed around as lambda expressions rather than values.
- Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.
这篇关于为什么要使用getter和setter / accessors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!