How to prevent the arrowhead anti-pattern

anti-patterns, c#, design-patterns

Solution

I'd go for the multiple `return` statements. This makes the code easy to read and understand.

Don't use `goto` for obvious reasons.

Don't use exceptions because the check you are doing isn't exceptional, it's something you can expect so you should just take that into account. Programming against exceptions is also an anti-pattern.

Problem

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.

Original source

Related problems