I've been reading up a lot about the cases where Optional
should be used.
A lot of the pages I've read say that Optional
shouldn't be used for private instance variables and instead should be returned by getters.
I would have thought that having private instance variables as optional would still be useful. If anybody looks at my code they can see that a value can be empty, instead of having to check the documentation to see if null could be returned.
In Scala null is never used and is only really there for interoperability with Java. It is recommended to always use an optional if a value can be null. This approach makes a lot more sense to me.
Here's a page mentioning it:
https://blog.joda.org/2015/08/java-se-8-optional-pragmatic-approach.html
Here is the example code.
private final String addressLine; // never null
private final String city; // never null
private final String postcode; // optional, thus may be null
// normal getters
public String getAddressLine() { return addressLine; }
public String getCity() { return city; }
// special getter for optional field
public Optional<String> getPostcode() {
return Optional.ofNullable(postcode);
}
The only advantage I can see is that if you want to serialize the object it is now possible as it isn't storing optional in a variable.
The disadvantage is that you don't know postcode could be null until you check the return type of the getter. If you were new to the code you might miss this add extend the class, causing a null pointer exception.
Here is a question asked about Scala's Option
.
Why is there a difference between Java and Scala with how optional should be used?