Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

nullpointerexception - Null checks for a complex dereference chain in Java 8

So I have a class generated by some contract (so no modifications allowed) with multiple data layers, I get it through soap request and then in my backend I have something like this:

value = bigRequest.getData().getSamples().get(0).getValuableData().getValue()

and in every dereference in that chain I can have null result. Class itself has no logic, just pure data with accessors, but nonetheless. I'm kinda sick of thought to make an ugly boilerplate of not-null checks for every single dereference, so I'm thinking of the best practice here:

  1. Actually make the ugly boilerplate (either with ifs or with asserts). I assume that its what I've got to do, but I have faint hopes.
  2. Do some Optional magic. But with no access to modify the source it'll probably be even uglier.
  3. Catch the NPE. It's ugly in its heart, but in this particular case I feel it's the best option, just because it's part of the logic, either I have that value or not. But catching NPE makes me shiver.
  4. Something I can't see by myself now.

I'm actually feel myself a little bit uncomfortable with this question cause I feel that NPE theme is explored to the bones, but I had no success in search.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I agree with both of you that Andrew Vershinin’s suggestion is the best we can do here and thus deserves to be posted as an answer.

nullableValue = Optional.ofNullable(bigRequest)
        .map(RequestCls::getData)
        .map(DataCls::getSamples)
        .filter(samples -> ! samples.isEmpty())
        .map(samples -> samples.get(0))
        .map(SampleCls::getValuableData)
        .map(ValDataCls::getValue)
        .orElse(null);

You will need to substitute the right class or interface names in the method references (or you may rewrite as lambdas if you prefer). Edit: If bigRequest itself cannot be null, the first method call should be just Optional.of(bigRequest).

It’s not the primarily intended use of Optional, but I find it OK. And better than items 1. and 3. (and 4.) from your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...