【发布时间】:2021-04-13 02:18:34
【问题描述】:
我已经使用 Spring Boot 创建了一个基本的 CRUD API,因为我已经为我的控制器创建了一个服务类。
以下是我的Controller的服务方法。
服务
public Customer updateCustomer(Customer newCustomer, Long customerId) throws ResourceNotFoundException {
return customerRepo.findById(customerId)
.map(customer -> {
if (newCustomer.getName() != null)
customer.setName(newCustomer.getName());
if (newCustomer.getGstin() != null)
customer.setGstin(newCustomer.getGstin());
if (newCustomer.getPhoneNumber() != null)
customer.setPhoneNumber(newCustomer.getPhoneNumber());
if (newCustomer.getAddress() != null)
customer.setAddress(newCustomer.getAddress());
if (newCustomer.getOutstandingBalance() != 0.0f)
customer.setOutstandingBalance(newCustomer.getOutstandingBalance());
return customerRepo.save(customer);
}).orElseThrow(() -> new ResourceNotFoundException());
}
我的问题是:是否可以简化使用多个 if 的代码?
如果有,任何人都可以建议简化处理这个逻辑..??
【问题讨论】:
-
如果您关心不覆盖已设置的属性,请使用
if。我可以将已经为空的属性设置为空,删除ifs -
就 Java 代码而言,没有其他结构可以更好地执行这种检查和设置的逻辑顺序。
-
你可以使用 Optional.of(newCustomer.getName).ifPresent(String s -> customer.setName(s)) 这样的东西,这样你就可以避免这一切,并且代码更清晰.
标签: java spring-boot