Recently I’ve been working on legacy vb.net code and during code peer review it was recommended not to use Exit Sub / Function but instead to nest all functionality in IF statements.
When I initially started developing I used to do it this way instinctively (Nest the IF’s), not only did it seem more logical, it just seemed less confusing.
However at some point I worked with a team that treated nested IF’s as “evil”, and so Exit subs / functions I was told was preferred. I’m pretty sure they produced some MS best practice material to back this up.
So this question is for experienced developers, which way is truly preferred? If you give an answer could you also please state your sources, or just mention that this is a preference preferred by your team / company / personal and give reasons.
Thanks in advance.
EDIT as requested: Code Samples
Exit Sub :
Private Sub DoSomeWork()
if not conditionMetFromAnotherFunction() then
exit Sub
end if
'Method work starts here
End Sub
Nested IFs:
Private Sub DoSomeWork()
if conditionMetFromAnotherFunction() then
'Method work starts here
end if
End Sub
As David pointed out in his comment, nested if statements can add to the complexity of your code.
Imagine the following (simplified) code :
Or the following
If your conditions get more complex, returning makes it much more easy to understand that under some conditions, your code is not doing anything, and makes your code more readable.
Otherwise, you have to read all the function and mentally parse the nested if’s to see that nothing’s done.