2

How can one create a java.nio.Path that represents no path no matter the environment?

I cannot call Path.of(<String>) and guarantee the resulting path to point to an invalid file or directory.

What I'm looking for is if there is a safer way to represent an empty / invalid path than using a null value.

ljleb
  • 182
  • 1
  • 14
  • maybe you could use /dev/null? – Paul Bastide Jan 20 '19 at 00:50
  • Yeah, that would work. But what about Windows users? – ljleb Jan 20 '19 at 00:52
  • I think NUL is reserved. https://stackoverflow.com/a/313115/1873438 – Paul Bastide Jan 20 '19 at 15:48
  • I didn't know windows had such a feature. That's cool! On the other hand, I think it is part of batch syntax more than a file in itself. And this is still system dependent. If I have unit tests on my Linux machine, I would have to change the "invalid file" path when I want to work on Windows... – ljleb Jan 29 '19 at 03:46

3 Answers3

4

Depending on your use case, there are a couple options:

  • If you are trying to return the path from a method, you can use Optional<Path> and return Optional.empty() to denote no path.
  • If this is a field in a class and that class implements some behavior, you can use the null object pattern to implement another class with the same interface that does "nothing" (whatever your application needs to do if there is no path).
casablanca
  • 69,683
  • 7
  • 133
  • 150
2

I wouldn't really try to create an invalid Path. It is not intended to be used that way. If you have a function that could return a Path, but in certain cases it would not, the best approach is to return Optional<Path>.

The advantage is that you will be forcing whoever is calling the function to check for the case where there is no valid Path. Unlike returning null, where if the caller forgets to check for it, he will just get the program blow up with a NullPointerException later on.

jbx
  • 21,365
  • 18
  • 90
  • 144
0

If you would like to avoid nulls, use Optional and then you can test for null/present.

cgp
  • 41,026
  • 12
  • 101
  • 131