Favor Optional Over Null

 class​ Communicator {
 
  Connection connectionToEarth;
 
 void​ establishConnection() {
 // used to set connectionToEarth, but may be unreliable
  }
 
  Connection getConnectionToEarth() {
»return​ connectionToEarth;
  }
 }

References that don’t point to an object point to the null reference instead. If you try to call a method on a null reference, you cause a NullPointerException. This is probably the most well-known exception in Java.

Using null references is fine for internal state where you have full control over how the reference is accessed. But exposing it makes the program fragile because every caller needs to check for null, which is something that people easily forget. This is what we’ve discussed ...

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.