This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I debugging an existing piece of code which looks like the following.
After start() is called, invocations on method1() and method2() can procede. If an exception is encountered in start(), conn might end up with the null value. And method1() and method2() will throw NPEs.
One way to handle the NPE is to: log them & silently default values back. e.g. I could return the empty Set in method1() and null in method2(). Or perhaps I could throw an IllegalStateException. Which one is better ? Are there other possible alternatives. Thanks
I would go for the IllegalStateException. A valid connection is a precondition of your methods. You definitely do not want to just return an empty Set when there is no connection. This can be taken as if there is just no data available at the moment, which could happen with a valid connection. A client attempting to use these methods without a valid connection might be buggy, so it's better to let it blow up with an exception.