I frequently get called in as a second pair of eyes when strange problems crop up in programs. With disheartening frequency, I run into an exception coming from a line of code where the return value of the first function is used to call a second function, which is used to call a third function, and so on. You know, like this:
This is a pain in the neck to troubleshoot, because the exception could have come from any of those functions. When you get an error from a line like this, you have a lot of troubleshooting to do. Even if you have a good debugger available (which is usually the case now in the J2EE world, but isn’t always the case if you’re using an older (or much newer) environment with poor debugging support), your situation isn’t necessarily better. If you don’t have source code for all the libraries in the chain available, you won’t be able to trace below this line.
Instead of the “chain of functions” approach, I do it like this:
retval1 = function1(arg1a, arg1b)
retval2 = retval1.function2(arg2a, arg2b)
retval3 = retval2.function3(arg3a,arg3b)
retval4 = retval3.function4(arg4a, arg4b)
This way, if you get a runtime exception, your stack trace will tell you exactly which line generated the problem. If you run the program in a debugger, you can see the values of all the objects as you step through. You do a bit more typing, but if you type as fast as most programmers, the difference is negligible. I’d rather spend 30 extra seconds typing than have to spend hours or days bug-hunting on a problem in a production system.