Alex Rivera | Logout

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

Asked 2012-07-09T12:03:19.530
8

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
Edit
Report

1 Answer

1

IMO nested if's are a very quick rout to horrid spaghetti code. Generally speaking if your deeply nesting you code then your trying to do to much work in your method and most likely will benefit from refactoring into smaller parts.

Having said that sometimes it cannot be avoided so there is no one answer fits all.

answered 2012-07-09T12:18:27.310

Your Answer