【问题标题】:JAVA populate a POJO void method vs methods which return fields which is better?JAVA填充POJO void方法与返回字段的方法哪个更好?
【发布时间】:2015-12-23 15:57:04
【问题描述】:

JAVA 1.8

从另一个类“Person”填充类“Customer”的最易读/最有效的方法是什么?

AddressInfo、ContactPreferencesAuthorizationRoles 都是具有多个字段的复杂 POJOS,我们需要进行额外的 DB 调用和服务调用。

public Customer getCustomerFromPerson(Person per) {
Customer cust = new Customer();
 populateAddressInfo(cust, per);
 populateContactPreferences(cust, per);
 populateAuthorizationRoles(cust, per);
 ...
 return cust;
}

vs

public Customer getCustomerFromPerson(Person per) {
Customer cust = new Customer();
 cust.setAddressInfo(getAddressInfoFromPerson(per));
 cust.setContactInfo(getContactPreferencesForCust(cust, per));
 cust.setAuthRoles(getAuthorizationRoles(per));
 ...
 return cust;
}

注意:

Customer.AddressInfo != Person.AddressInfo。它们是非常少的映射,我们从 DB/Soap 中提取额外数据以获取完整的 Customer.Addressinfo cust.getAddressInfo.setIsBillingAddress(Webservicecall(per.getAddressInfo));

【问题讨论】:

  • 为什么你的人没有 getter,比如 person.GetAddressInfo ?
  • 您解释的方式是使用不同名称的设置器,直到您每次调用 populate*() 都返回一个新客户。我认为将它们作为设置器使其更具可读性。
  • 地址信息是客户所需的完整地址信息,即 cust.getAddressInfo != per.getAddressInfo。除了 Person.Addressinfo 中的所有数据之外,Customer.AddressInfo 还需要更多信息、类型转换和额外的服务调用
  • 你可以实现一个builder模式 link

标签: java jakarta-ee memory-management coding-style pojo


【解决方案1】:

我建议你看看 Apache BeanUtils.copyProperties

public static void copyProperties(Object dest, Object orig)
           throws IllegalAccessException, InvocationTargetException

它可能会更快地执行您想要的操作,但可能会影响类型安全和性能。

链接:BeanUtils

【讨论】:

  • Customer 和 Person 的一对一映射很少,所以这不太合适。客户需要大量额外的数据才能完整-谢谢
猜你喜欢
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2013-03-31
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
相关资源
最近更新 更多