简体   繁体   English

获取/设置者或属性图

[英]getter/setter or map for properties

I have a question about best practices to use properties in pojo class. 我对在pojo类中使用属​​性的最佳做法有疑问。 Basically, I see that pojo class have getters/setters for private fields. 基本上,我看到pojo类具有用于私有字段的getter / setter方法。 It is easy to manipulate the properties but no so much flexibility(if we want to add additional property we will need to change minimum one class). 操作属性很容易,但是没有那么多的灵活性(如果要添加其他属性,我们将需要更改至少一个类)。

But there is another option to use properties(especially if you have too much properties) using Collection for them(Map, Set, etc.). 但是还有另一种选择来使用属性(特别是如果您有太多属性),而使用Collection(地图,集合等)。 In this case there is no need to change class if we want to add some new properties.The bad of this option, from my opinion, is that it will be a bit harder to get some kind of properties due to keys mistakes. 在这种情况下,如果我们要添加一些新属性,则无需更改类。从我的角度来看,此选项的缺点是,由于按键错误,获取某种属性会有些困难。 What best practices could be applied for this topic? 哪些最佳实践可以应用于此主题?

The bad of this option, from my opinion, is that it will be a bit harder to get some kind of properties due to keys mistakes. 我认为,此选项的弊端在于,由于按键错误而很难获得某种属性。

That's one of the problems with doing that, yes. 这是这样做的问题之一 ,是的。 Another is that using a property that doesn't exist becomes a runtime error instead of a compile-time error. 另一个问题是,使用不存在的属性将导致运行时错误,而不是编译时错误。 And that unless all of the property values are the same type, you either have to use an untyped collection and cast everything all over the place ( f = (int)obj.get("foo"); ), or use several typed collections and always use the correct one ( f = obj.getInt("foo"); ). 而且,除非所有属性值都是相同的类型,否则您要么必须使用无类型的集合并将所有内容f = (int)obj.get("foo");转换为整个位置( f = (int)obj.get("foo"); ),要么使用多个有类型的集合并始终使用正确的( f = obj.getInt("foo"); )。

What best practices could be applied for this topic? 哪些最佳实践可以应用于此主题?

Use proper properties, not a collection of name-value pairs. 使用适当的属性,而不是名称/值对的集合。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM