我对“如何正确地做这件事”有点困惑:
// return true: if present and number of lines != 0
boolean isValid(Optional<File> optFile) {
return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
}
private boolean isZeroLine(File f) {
return MyFileUtils.getNbLinesByFile(f) == 0;
}
我知道语法不正确,不能编译,但这只是你的想法。
我怎么才能把它变成“干净的代码”呢?例如,避免做以下事情:
if (optFile.isPresent()) {//} else {//}
发布于 2018-10-03 09:50:05
处理布尔返回类型(很容易推断出Predicate
),一种方法是使用Optional.filter
:
boolean isValid(Optional<File> optFile) {
return optFile.filter(this::isZeroLine).isPresent();
}
但是,使用Optional
的参数似乎是一种糟糕的做法。正如卡洛斯在评论中所建议的那样,实现它的另一种方式可能是:
boolean isValid(File optFile) {
return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
另一方面,ifPresentOrElse
是在执行与存在Optional
值相对应的某些操作时使用的构造,例如:
optFile.ifPresentOrElse(this::doWork, this::doNothing)
其中相应的动作可以是-
private void doWork(File f){
// do some work with the file
}
private void doNothing() {
// do some other actions
}
https://stackoverflow.com/questions/52617309
复制相似问题