Java 带有 Getter/Setter 的私人列表 vs 公共列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23983415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Private List with Getter/Setter vs Public List
提问by dalawh
Would it be better to make a global List in a class private and have getter and setter methods or would it be better to just make it public? What is the standard in Java?
将类中的全局 List 设为私有并具有 getter 和 setter 方法会更好,还是仅将其设为公开会更好?Java的标准是什么?
I was taught to make variables private, and just have getter and setter methods, but it definitely looks better accessing a public list than a private one.
我被教导将变量设为私有,并且只有 getter 和 setter 方法,但访问公共列表肯定比访问私有列表更好。
public exampleclassThatContainsTheList.goodieList.add("Candy");
private exampleclassThatContainsTheList.setGoodieList(exampleclassThatContainsTheList.getGoodieList().add("Candy"));
That's my opinion, but of course I would prefer to go by standards than to go by what looks good.
这是我的意见,但当然我更愿意按照标准而不是看起来不错。
回答by NitroStoutPlz
The standard is to have private instance variables and public getter/setter methods (like you were taught). You always want to encapsulate or "hide" data, that is one of the fundamental concepts of OOP. One of the main benefits of this (among others) is to modify our implemented code without breaking the code of other developers who may be using the same code. This approach will also add maintainability.
标准是拥有私有实例变量和公共 getter/setter 方法(就像你被教导的那样)。您总是希望封装或“隐藏”数据,这是 OOP 的基本概念之一。这样做的主要好处之一(除其他外)是修改我们实现的代码,而不会破坏可能使用相同代码的其他开发人员的代码。这种方法还将增加可维护性。
回答by Thomas Junk
I would go one step further:
我会更进一步:
Why should anyone know how you store your data? Information hidingis the keyword. In your example details about the datatype leakto the outside. The keyword listleaks details about the implementation, which is 1) unnecessary information - you could even name it treasurechest2) does a possible user of your class make assumptions about the implementation, which is a bad thing. Give your class a domain-name like goodiesand name the methods like put/ pull. If you want to add multiple elements I would use a more generic Interface like Iterable.
为什么有人应该知道您如何存储数据?信息隐藏是关键词。在您的示例中,有关数据类型泄漏到外部的详细信息。关键字列表泄漏了有关实现的详细信息,即 1) 不必要的信息 - 您甚至可以将其命名为珍宝箱2) 您的类的可能用户是否对实现进行了假设,这是一件坏事。给你的类一个域名,比如好东西,把方法命名为put/ pull。如果你想添加多个元素,我会使用更通用的接口,比如Iterable。
回答by rachana
It be better to make a global List in a class private and have getter and setter methods
最好在一个私有类中创建一个全局 List 并具有 getter 和 setter 方法
There are some advantages of using getter/setter
使用 getter/setter 有一些优点
- getters and setter can have validation in them, fields can't
- using getter you can get subclass of wanted class.
- getters and setters are polymorphic, fields aren't
- debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
- they can hide implementation changes
- getter 和 setter 可以在其中进行验证,字段不能
- 使用 getter 你可以获得想要的类的子类。
- getter 和 setter 是多态的,字段不是
- 调试可以简单得多,因为断点可以放置在一个方法中,而不是该给定字段的许多引用附近。
- 他们可以隐藏实施更改
To know in more detail go through following links
要了解更多详细信息,请访问以下链接
Advantage of set and get methods vs public variable
:
:
回答by Luiggi Mendoza
First at all, you should not use public
fields directly unless they are constant (static final
) fields and making sure their state won't change. They should be exposed using Encapsulationto avoid a client of your class modifying the state. Here's an example when writing your own framework by implementing getter/setter in defensive way, in order to not alter the current state of your List
:
首先,您不应该public
直接使用字段,除非它们是常量 ( static final
) 字段并确保它们的状态不会改变。它们应该使用封装来公开,以避免您的类的客户端修改状态。这是通过以防御方式实现 getter/setter 来编写自己的框架的示例,以便不改变您的当前状态List
:
public class Foo {
private List<String> stringList;
public Foo() {
//always initialized, never null
this.stringList = new ArrayList<>();
}
public List<String> getStringList() {
//defensive implementation
//do not let clients to alter the state of the list
//for example, avoiding clear the list through getStringList().clear()
return new ArrayList(stringList);
}
public void setStringList(List<String> stringList) {
//defensive implementation
//do not let clients to pass a null parameter
this.stringList = (stringList == null) ? new ArrayList<>() : new ArrayList<>(stringList);
}
}
Apart of this, the JavaBean specificationstates that fields in a Java class should not be public
and their access should be through getter and setter methods.
除此之外,JavaBean 规范规定 Java 类中的字段不应该是public
,它们的访问应该通过 getter 和 setter 方法。
7 Properties
Properties are discrete, named attributes of a Java Bean that can affect its appearance or its behavior. For example, a GUI button might have a property named “Label” that represents the text displayed in the button.
Properties show up in a number of ways:
- Properties may be exposed in scripting environments as though they were fields of objects. So in a Javascript environment I might do “b.Label = foo” to set the value of a property.
- Properties can be accessed programmatically by other components calling their getter and setter methods (see Section 7.1 below).
(...)
7.1 Accessor methods
Properties are always accessed via method calls on their owning object. For readable properties there will be a gettermethod to read the property value. For writable properties there will be a settermethod to allow the property value to be updated.
7 属性
属性是 Java Bean 的离散命名属性,可以影响其外观或行为。例如,一个 GUI 按钮可能有一个名为“标签”的属性,表示按钮中显示的文本。
属性以多种方式显示:
- 属性可以在脚本环境中公开,就好像它们是对象的字段一样。因此,在 Javascript 环境中,我可能会执行“b.Label = foo”来设置属性的值。
- 其他组件可以通过调用其 getter 和 setter 方法以编程方式访问属性(请参阅下面的第 7.1 节)。
(……)
7.1 存取方法
属性总是通过对它们拥有的对象的方法调用来访问。对于可读属性,将有一个getter方法来读取属性值。对于可写属性,将有一个setter方法来允许更新属性值。
There are frameworks that follow these specifications in order to allow injection/retrieval of values for class fields through reflection. For example, Spring and JSF.
有一些框架遵循这些规范,以便允许通过反射注入/检索类字段的值。例如,Spring 和 JSF。
Spring example through XML configuration:
通过 XML 配置的 Spring 示例:
<bean id="fooBean" class="my.package.Foo">
<property name="stringList">
<list>
<value>Hello</value>
<value>World</value>
</list>
</property>
</bean>
And the associated Java class:
以及相关的 Java 类:
package my.package;
public class Foo {
private List<String> stringList;
public String getStringList() {
return this.stringList;
}
//allows Spring to set the value of stringList through reflection
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
}
JSF example for field binding using Expression Language:
使用表达式语言进行字段绑定的 JSF 示例:
<!-- allows JSF to call getter through reflection -->
<h:dataTable value="#{foo.stringList}" var="value">
<h:column>
#{value}
</h:column>
</h:dataTable>
And the associated Java class:
以及相关的 Java 类:
package my.package;
@ManagedBean
@ViewScoped
public class Foo {
private List<String> stringList;
@PostConstruct
public void init() {
stringList = new List<>();
stringList.add("Hello");
stringList.add("world");
}
public String getStringList() {
return this.stringList;
}
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
}
Which option to use: Defensive getter/setter or common getter/setter? It will depend on what you're doing.
使用哪个选项:防御性 getter/setter 或普通 getter/setter?这将取决于你在做什么。