具有映射的类的 getter/setter
为包含映射的类实现/提供 getter/setter 的最佳实践是什么?
我看到的最常见的实现是:
public class MyClass {
private Map<String, String> myMap;
public getMyMap() { /* Return an unmodifiable map */ }
public setMyMap(Map<String, String> myMap) { ... }
}
或者提供一个像这样的接口会更好:
public getMyMap() { /* Return a modifiable map */ }
public addToMap(String key, String value) { myMap.put(key, value); }
为什么这样的方法更好?
What is the best practice in implementing/providing getters/setters for a class containing a map?
The most common implementation I see is:
public class MyClass {
private Map<String, String> myMap;
public getMyMap() { /* Return an unmodifiable map */ }
public setMyMap(Map<String, String> myMap) { ... }
}
Or would it be better to provide an interface like:
public getMyMap() { /* Return a modifiable map */ }
public addToMap(String key, String value) { myMap.put(key, value); }
And why is such method better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两者都有其用途。 类公开的方法应该具有适当的抽象级别。例如,如果该类是由
Map
支持的狗注册表,则它可以提供如下方法:如果说一个规则引擎允许客户端在一次调用中指定整个规则集,那么它可以公开如下方法:
Both have their uses. The methods exposed by a class should be of a proper level of abstraction. For example if the class is a registry of dogs backed by a
Map<String, Dog>
, then it could provide methods like:If it's say a rule engine that allows clients to specify the entire rule set in one call, then it could expose methods like:
一般来说,我会说尽量不要归还地图。有一个接受键并返回值的方法。获取地图就可以,只要复制它即可,但我更喜欢采用键/值并将其放入地图的方法。
如果您必须归还地图,则应归还只读版本或其副本。 set 方法还应该复制映射。
允许调用者在类不知道的情况下改变类内部的数据是一个坏主意,传递或保留可变数据也是一个坏主意。
In general I would say try not to return the map at all. Have a method that takes the key and returns the value. Taking a map is ok, as long as you copy it, but a method that takes the key/value and puts it into the map would be my preference.
If you must return the map you should return a read-only version or a copy of it. A set method should also copy the map.
It is a bad idea to allow callers to mutate the data inside of a class without the class knowing, passing or holding onto mutable data is a bad idea.
这完全取决于您的要求。在大多数情况下这可能就足够了。
您甚至可能没有返回映射的 getter 方法。如果您使用我的插件,它可能会帮助您创建这些方法: http ://fast-code.sourceforge.net/documentation.htm#create-list-map 因为 Eclipse 不会帮助您创建 add 方法。
It totally depends on your requirement. This may suffice in most of the cases.
You may not even have a getter method that returns the map. If you use my plug-in, it may help you creating those methods : http://fast-code.sourceforge.net/documentation.htm#create-list-map as eclipse will not help you create the add method.
我只想提供一个。就像......
当你想使用它时,
免责声明:我没有编译这个并测试这个答案;)
I would just provide one. Something like...
and when you want to use it then
DISCLAIMER: I did not compile this and test this answer ;)