VDanyliuk
VDanyliuk

Reputation: 1049

Get() pattern to avoid nullPointerException

I have get link like this:

record.getRootElement().getChild("Data").getAttributeValue("attr");

And this getters can return null. Is there some pattern to avoid this exception without checking all results?

Upvotes: 2

Views: 62

Answers (1)

Stephen C
Stephen C

Reputation: 718986

How about something like this:

String path = "/Data:attr";
String value = lookup(record, path);
...

where you implement the lookup method to parse the path, and then perform the corresponding sequence of "get" operations. If you so choose, the lookup method could be designed to return null if some intermediate "get" in the sequence returned null. (I wouldn't do that. I would throw an exception.)

Obviously, this approach has a significant performance penalty. However, it should be:

  • more robust than a hard-coded get sequence (where you might forget a null test),
  • more concise, and
  • more flexible.

Upvotes: 1

Related Questions