In normal programming style, logics are organized into statements, each takes one line. e.g.
statement A;
statement B;
statement C;
...
When a bug occurs, the compiler tells me the line number of failing statement. I can easily debug with this narrowed-down scope.
However, now that fluent style code is used (e.g. in Java Stream APIs), long blocks of logic are written in one statement in the form of chained method. For example:
methodA()
.methodB()
.methodC()
.methodD()
....
When failure happens, what is a good way to narrow down to which chained method fails? My concern is that compiler's debug hint only has a line number, but the entire chained block is contained in this one line statement, which is not very helpful for debugging.
Code the chained methods on different lines.
When chained methods are coded on different lines, the stacktrace contains the line number of the method call that failed.
For example:
public class MyClass {
MyClass okMethod() {
return this;
}
MyClass explodingMethod() {
throw new RuntimeException(); // line 10
}
public static void main(String[] args) {
new MyClass()
.okMethod()
.explodingMethod() // line 16
.okMethod();
}
}
Executing this causes an exception with this stacktrace:
Exception in thread "main" java.lang.RuntimeException
at MyClass.explodingMethod(MyClass.java:10)
at MyClass.main(MyClass.java:16) // this is the call that exploded
Note that the line number within the stacktrace shows which actual method invocation exploded.