Optional
type introduced in Java 8 is a new thing for many developers.
Is a getter method returning Optional
type in place of th
If you are using modern serializers and other frameworks that understand Optional
then I have found these guidelines work well when writing Entity
beans and domain layers:
null
value for a cell in column BAR
in table FOO
, then the getter Foo.getBar()
can return Optional
indicating to the developer that this value may reasonably be expected to be null and they should handle this. If the DB guarantees the value will not be null then the getter should not wrap this in an Optional
.Foo.bar
should be private
and not be Optional
. There's really no reason for it to be Optional
if it is private
.Foo.setBar(String bar)
should take the type of bar
and not Optional
. If it's OK to use a null
argument then state this in the JavaDoc comment. If it's not OK to use null
an IllegalArgumentException
or some appropriate business logic is, IMHO, more appropriate. Optional
arguments (for reasons similar to point 3). Generally I only include arguments in the constructor that must be non-null in the serialization database.To make the above more efficient, you might want to edit your IDE templates for generating getters and corresponding templates for toString()
, equals(Obj o)
etc. or use fields directly for those (most IDE generators already deal with nulls).