I'm a bit confused about how to best refactor my code into something more readable.
Consider this piece of code:
var foo = getfoo();
if(foo!=null)
{
var bar = getbar(foo);
if(bar!=null)
{
var moo = getmoo(bar);
if(moo!=null)
{
var cow = getcow(moo);
...
}
}
}
return;
As you can see, lots of nested if
blocks, needed because each nested if is dependent on the previous values.
Now I was wondering how to make my code a bit cleaner in this regard.
Some options I have thought of myself would be to:
- return after each if clause, meaning I'd have multiple places where I leave my method
- throw
ArgumentNullException
s, after which I'd catch them in the end and place the return statement in my finally clause (or outside the try/catch block) - work with a label and
goto:
Most of these options seem a bit "dirty" to me, so I was wondering if there was a good way to clean up this mess that I've created.