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
If you don't exit your functions early, you will reach a point where your code looks like this:
No one can tell me this is a better style than returning early from a function.
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}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With