更新 Java 对象的多个字段的最佳方法
我想一次更新 Java 对象的多个字段以对更新进行检查。我的想法如下:
SomethingValues values = new SomethingValues();
values.name = "abc";
values.amount = 12;
values.weight = 42.2;
...
something.update(values);
另一种选择是 SomethingValuesBuilder
,但我认为构建器所需的额外代码在这里是不必要的。
如果我要使用 setter……
something.setName("abc"); // would perform check
something.setAmount(12); // would perform check
...
我需要对每个 setter 执行检查,而不是只对 update
方法中的所有字段执行一次检查。
有没有比用附加值对象 (values
) 更新域对象 (something
) 更好的主意呢?
I want to update multiple fields of a Java object at once to perform a check on the update. My idea looks like this:
SomethingValues values = new SomethingValues();
values.name = "abc";
values.amount = 12;
values.weight = 42.2;
...
something.update(values);
An alternative would be a SomethingValuesBuilder
, but I think that the additional code needed for a builder is not necessary here.
If I would use setters ...
something.setName("abc"); // would perform check
something.setAmount(12); // would perform check
...
... I'd need to perform the check on each setter instead of only one time for all fields in the update
method.
Is there any better idea than updating the domain object (something
) with an additional value object (values
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常会选择
SomeObjectType.update(parameters)
,其中对象负责检查和设置所有参数,并最终抛出IllegalArgumentException
,以防某些参数不正确。公认。通过这种方式,您可以获得更好的可读性和封装性。I usually go for the
SomeObjectType.update(parameters)
in which the object is responsible of checking and setting all parameters and eventually throw anIllegalArgumentException
in case some of the parameters are not accepted. This way you acheive better readability and encapsulation.我想最常用的是
Map
因为它不需要任何额外的类。示例:
Beanutils.populate(Object bean, Map 属性)
来自 commons / beanutilsBeanWrapper
技术也使用了 Maps 并集成了验证I guess what's most commonly used is a
Map<String, Object>
because it doesn't require any extra classes.Examples:
Beanutils.populate(Object bean, Map properties)
from commons / beanutilsBeanWrapper
technology also uses Maps and integrates validation