5

I am a little confused on "how to do this properly":

 // 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;
 }

I know the syntax is not correct and not compiling, but it's just for you to get the idea.

How can I turn this into 'clean code'? i.e. avoid doing:

if (optFile.isPresent()) {//} else {//}
Naman
  • 27,789
  • 26
  • 218
  • 353
Tyvain
  • 2,640
  • 6
  • 36
  • 70
  • 3
    kind of `optFile.map(this::isZeroLine).orElse(false)` ? but not sure if having an optional as argument is a good idea – user85421 Oct 02 '18 at 22:35
  • @CarlosHeuberger That's it ! – Tyvain Oct 02 '18 at 22:35
  • It is becoming impossible to read Java.. – Koray Tugay Oct 03 '18 at 02:30
  • @Tyvain Both [`map`](https://stackoverflow.com/questions/52617309/java-10-ifpresentorelse-that-return-boolean#comment92168796_52617309) and [`filter`](https://stackoverflow.com/a/52618642/2525313) are good solutions. Re having an `Optional` parameter, don't succumb to the [majority opinion](https://stackoverflow.com/a/23464794/2525313) ([minority report](https://stackoverflow.com/a/27071576/2525313)). If you already have an `Optional`, there is no need to unpack it to avoid the `Optional` parameter. – Nicolai Parlog Oct 03 '18 at 07:36

1 Answers1

5

Dealing with boolean return type(easily inferred Predicates), one way to do that could be to use Optional.filter :

boolean isValid(Optional<File> optFile) {
    return optFile.filter(this::isZeroLine).isPresent();
}

But, then using Optionals arguments seems to be a poor practice. As suggested in comments by Carlos as well, another way of implementing it could possibly be:

boolean isValid(File optFile) {
    return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}

On another note, ifPresentOrElse is a construct to be used while performing some actions corresponding to the presence of the Optional value something like :

optFile.ifPresentOrElse(this::doWork, this::doNothing)

where the corresponding actions could be -

private void doWork(File f){
     // do some work with the file
}

private void doNothing() {
     // do some other actions
}
Naman
  • 27,789
  • 26
  • 218
  • 353