[英]Best practice to access static object, 'public static' or 'private static' with getter
I have a class Foo
which contain a static Map<String, String> myMap
and some public static
methods which manipulate myMap
. 我有一个
Foo
类,其中包含一个static Map<String, String> myMap
和一些操作myMap
public static
方法。
myMap
is common Map("common content") for some classes in my project. myMap
是项目中某些类的通用Map(“通用内容”)。
Those classes, which need myMap
, only read data from it and always change data from myMap
using methods from Foo
. 这些需要
myMap
类myMap
其中读取数据,并始终使用Foo
方法更改myMap
数据。
My question is: How is the best practice to declare and access myMap
, in my case? 我的问题是:在我的情况下,最佳实践是如何声明和访问
myMap
? As public static
and access like Foo.myMap
or as private static
and acces like Foo.getMyMap()
which will return a copy of myMap
( new HashMap<String, String>(myMap)
). 作为
public static
Foo.myMap
和访问权(如Foo.myMap
或作为private static
Foo.myMap
和访问Foo.getMyMap()
如Foo.getMyMap()
,这将返回myMap
的副本( new HashMap<String, String>(myMap)
)。 Or this depends only by my preferences? 还是这仅取决于我的喜好?
Follow these steps in the following order: 请按照以下顺序执行以下步骤:
static
in general, because it is not in regards to OOP principles. static
,因为它与OOP原则无关。 static
, the field must be final
regardless of the access way usage. static
,则该字段必须是final
而不管访问方式的使用情况如何。 getters
over public
visibility modifier. public
可见性修饰符,更喜欢使用getters
剂。 But yes, it depends always to your preferences. 但是,是的,这始终取决于您的偏好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.