Stephen Colebourne's blog: Java SE 8 Optional, a pragmatic approach
Java SE 8 Optional, a pragmatic approach
The Optional
classs in Java 8 is a useful tool to help developers manage data. But advice on how to use it varies. This is my take on one good approach to using Optional
in Java 8.
Note that this article assumes you know what Optional
is and how it works. See my previous article and other tutorials for more info. Also, be aware that Optional
is a heavily argued topic, with some commentators liable to get rather too excited about its importance.
A pragmatic approach to Optional in Java 8
What follows is a specific approach to using Optional
in Java 8 that I have found very useful. It should be considered that the approach has been developed in terms of writing a new application, rather than maintaining an existing one. There are five basic points:
- Do not declare any instance variable of type
Optional
. - Use
null
to indicate optional data within the private scope of a class. - Use
Optional
for getters that access the optional field. - Do not use
Optional
in setters or constructors. - Use
Optional
as a return type for any other business logic methods that have an optional result.
Read full article from Stephen Colebourne's blog: Java SE 8 Optional, a pragmatic approach
No comments:
Post a Comment