0

How to avoid hard-to-trace errors from chained methods throwing null pointer exception.

I recently saw chained method calls and a null pointer exception was being thrown from one of them.

instance.method0().method1().method2().method3();

What is the best way to write code that avoids the hard-to-trace NP exception?

Is it from having each of the chained methods return only an Optional where a null reference may have been returned - or is there a better way?

likejudo
  • 2,946
  • 6
  • 45
  • 90
  • 1
    As you have found out chaining methods have some significant drawback. Therefore my advice is to not chain and instead call each method individually and save it's result for the next call. – Robert Jul 17 '21 at 16:02

0 Answers0