Should I use Java8/Guava Optional for every method that may return null?

后端 未结 3 1006
长情又很酷
长情又很酷 2020-12-23 00:00

Optional is used to represent nullable object, Some uses of this class include

  1. As a method return type, as an alternative to returning null to
    indicate tha
3条回答
  •  失恋的感觉
    2020-12-23 00:07

    As an observation, I think one of the most important aspects that have to be considered when architecting an application is to decide how to treat the "null problem". In this respect, the first step would be to identify possible "sources" of nulls. For example, the database or external libraries used in the project. The next step would be to 'contain' the problem, namely, to wrap problematic code(using Optional) and thus block the propagation of null throughout the system, where unsuspecting code might trigger NPEs.
    To answer your question, it depends...Most of the times I would say that's unnecessary, since it creates a lot of work with no value (for example, I wouldn't use optional for methods that call other private methods inside classes, or for methods that call methods of package-private classes), but code that exists at the thin boundary of different 'concerns' (or layers) in your application, (the signature of the interfaces/classes that you use to query the datastore, for example, or pojos used for 'transporting' data that might have null properties - DTOs, or, a more general description, published APIs of different modules) should avoid 'leaking' nulls into some other areas with different concerns.

提交回复
热议问题