我只是想知道以下是否是 Optional 的错误用例。可能是,因为它看起来很讨厌。
(这是关于调用返回空值的“传统”代码。)
private static class Person {
private Address address;
private String name;
}
private static class Address {
private Integer housenr;
private String houseletter;
private String street;
}
public String getAddress(Person person) {
return Optional.ofNullable(person.getAddress())
.map(x -> Optional.ofNullable(x.getHousenr()).map(y -> y + " ").orElse("") +
Optional.ofNullable(x.getHouseletter()).map(y -> y + " ").orElse("") +
Optional.ofNullable(x.getStreet()).orElse(""))
.orElse("<unknown>");
}
// unit test if string representation of an address is properly generated
assertThat(getAddress(charlesBabbage))
.isEqualTo("4 l Regentstreet");
我可能应该将代码放在 Person 类和 Address 类的方法中,这样就不会太困扰我了。
或者我应该用“旧方式”来做:
public String getAddress(Person person) {
if (person.getAddress() == null) {
return "<unknown>";
}
StringBuilder builder = new StringBuilder();
if (person.getAddress().getHousenr() != null) {
builder.append(person.getAddress().getHousenr() + " ");
}
if (person.getAddress().getHouseletter() != null) {
builder.append(person.getAddress().getHouseletter() + " ");
}
if (person.getAddress().getStreet() != null) {
builder.append(person.getAddress().getStreet() + " ");
}
return builder.toString();
}
请记住,这只是一个示例。可以添加更多字段,例如词缀、邮局、城镇/城市、自治市、州、国家(更不用说外国地址),从而加剧问题。