简体   繁体   中英

How to represent an empty / invalid java.nio.Path

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.

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).

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.

如果您想避免空值,请使用 Optional,然后您可以测试空值/存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM