我正在使用 Java 中的 Optional 和 lambdas 编写代码,并且想知道在以下情况下最好的方法是什么:
public Optional<BObject> readIndexMaybe(String ref) {
try {
return Optional.ofNullable(index.read(ref)).map(BObjectBuilder::build);
} catch (IOException e) {
LOGGER.error(String.format("Could not read index of ref: %s, error: %s", ref, e));
}
return Optional.empty();
}
public Optional<BObject> readMaybe(String ref) {
Optional<BObject> bObject = readIndexMaybe(ref);
return bObject.flatMap(boMaybe -> { <---- HERE
try {
LOGGER.debug(String.format("Object read: %s", ref));
BObject obj = new BObjectBuilder(boMaybe).stream(loadDocumentStream(boMaybe)).build();
return Optional.of(obj);
} catch (IOException e) {
LOGGER.error(String.format("Could not read file with ref: %s, error: %s", ref, e));
}
return Optional.empty();
});
}
Optional<BObject>使用返回 an然后使用它作为返回类型flatMap接收的 lambda 函数会更好,还是在 lambda 内部返回然后只使用会更好:Optional<BObject>nullmap
public Optional<BObject> readIndexMaybe(String ref) {
try {
return Optional.ofNullable(index.read(ref)).map(BObjectBuilder::build);
} catch (IOException e) {
LOGGER.error(String.format("Could not read index of ref: %s, error: %s", ref, e));
}
return Optional.empty();
}
public Optional<BObject> readMaybe(String ref) {
Optional<BObject> bObject = readIndexMaybe(ref);
return bObject.map(boMaybe -> { <--- HERE
try {
LOGGER.debug(String.format("Object read: %s", ref));
return new BObjectBuilder(boMaybe).stream(loadDocumentStream(boMaybe)).build();
} catch (IOException e) {
LOGGER.error(String.format("Could not read file with ref: %s, error: %s", ref, e));
}
return null;
});
}
第一种方法对我来说似乎稍微好一点,因为我可能会在其他地方重用 lambda 函数,但它不会返回null但是Optional. 但是,只要我只在一个地方使用它就值得吗?
UYOU
小唯快跑啊
相关分类