Should Java 8 getters return optional type?

后端 未结 5 1244
自闭症患者
自闭症患者 2020-11-22 05:42

Optional type introduced in Java 8 is a new thing for many developers.

Is a getter method returning Optional type in place of th

5条回答
  •  故里飘歌
    2020-11-22 06:16

    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:

    1. If the serialization layer (usually a DB) allows a 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.
    2. Foo.bar should be private and not be Optional. There's really no reason for it to be Optional if it is private.
    3. The setter 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.
    4. Constructors don't need 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).

提交回复
热议问题