Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is preferred : Nested If's or Exit Sub / Function?

Tags:

.net

vb.net

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
like image 876
JL. Avatar asked Jul 09 '12 12:07

JL.


2 Answers

If you don't exit your functions early, you will reach a point where your code looks like this:

stumble on code

No one can tell me this is a better style than returning early from a function.

like image 151
sloth Avatar answered Sep 19 '22 08:09

sloth


during code peer review it was recommended not to use Exit Sub / Function but instead to nest all functionality in IF statements.

This is horrible advice. It’s as simple as that. Ignore it. In fact, the opposite is usually true, especially in situations where nested indentation would be required, or where you check your parameters for validity and might exit early: the code in your question is a good example of that. Do use early exit here.

There is no “official” source for that (what would be official?) but it’s pretty much consensus among good programmers, with a very small minority who opposes this. For more discussion about this see the discussion on Programmers.

However, I’d advise using Return instead of Exit {Sub|Function}.

like image 29
Konrad Rudolph Avatar answered Sep 20 '22 08:09

Konrad Rudolph