Hi I have written a little function like
public void foo(MyClassA paraA) {
if (paraA == null) return;
MyClassB paraB = doSomeStuff(paraA);
if (paraB == null) return;
MyClassC paraC = doMoreStuff(paraB);
if (paraC == null) return;
....
}
The above fails fast and is nice to read (i.e. the intention to return on null values is clear). But now instead of simply returning, I want to do some error logging, so I changed to
public void foo(MyClassA paraA) {
if (paraA == null) {doLog(); return;}
MyClassB paraB = doSomeStuff(paraA);
if (paraB == null) {doLog(); return;}
MyClassC paraC = doMoreStuff(paraB);
if (paraC == null) {doLog(); return;}
....
}
The above is also clean and easy to read, but I have to repeat doLog() a couple of times. So I change again to
public void foo(MyClassA paraA) {
if (paraA != null) {
MyClassB paraB = doSomeStuff(paraA);
if (paraB != null) {
MyClassC paraC = doMoreStuff(paraB);
if (paraC != null) {
....
return;
}
}
}
doLog();
}
The above calls doLog() only just once but I ended with some deeply-nested if statements, which are very ugly and hard to read. So how do I keep the same cleanliness like before and have doLog() just once? Note that returning something else rather than void for foo() is not allowed. And I also read that using try/catch as oppose to null check is an anti-pattern.
If I am to try, I want to write something like
public void foo(MyClassA paraA) {
while(true) {
if (paraA == null) break;
MyClassB paraB = doSomeStuff(paraA);
if (paraB == null) break;
MyClassC paraC = doMoreStuff(paraB);
if (paraC == null) break;
....
return;
}
doLog();
}
The above fulfills all my needs(fail fast, clean, no nested if), but is the use of the while loop here an anti-pattern as the while loop here is never meant to run more than once?