Let’s say, we have a model class called Employee. Some of the fields of Employee could be null. If these null values are not handled properly by the caller, this could lead to NPEs(Null pointer exception). Optionals is the library provided by java for cleaner way to handle null values and avoid NPEs. So it makes sense to use Optional methods in our model class.
But there is a catch, as per this response on stack overflow, Java optionals were not designed to be
- passed as parameters
- to be field of an object
- when return is an array/list of objects.
Java optionals are not serializable and so if we want to serialize/deserialize our model, optional fields would make that difficult.
If we would want our model to have optional fields, then we will have to find other ways to do that. Some of the different ways to use optionals in models are –
- As jackson supports serializing/deserializing objects with optional fields, use them in your project/package. (src)
- Spring 4.x supports serializing/deserializing objects with optional fields, so that option can be looked into.
- Create your own optional which is serializable/deserializable.
Thanks for stopping by. Have you ever come across a situation where you have to use Optionals where they are not intended to be? Share your thoughts by adding comments below.