Avoid Optional Fields or Parameters

 class​ Communicator {
 
» Optional<Connection> connectionToEarth;
 
»void​ setConnectionToEarth(Optional<Connection> connectionToEarth) {
 this​.connectionToEarth = connectionToEarth;
  }
» Optional<Connection> getConnectionToEarth() {
 return​ connectionToEarth;
  }
 }

In Favor Optional Over Null, you’ve seen that you should rather return Optional values instead of null references. When people learn about Optional, they start to apply it everywhere and for everything. Don’t make this mistake! There are situations where Optional can make your code more complicated and inconvenient to use. So let’s go over where you should avoid it.

In the code above, we have an Optional field with a setter and getter. ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.