Function return value

J

Jay

In a VBA function, a value is returned by assigning the function name
to the value. Can this be done in several places (CODE EXAMPLE 1), or
should it only be done once at the end of the function, with a
variable being used to temporarily hold the return value (CODE EXAMPLE
2)?

CODE EXAMPLE 1
Function Test() as integer
Test = 0
If ??? then
Test = 1
Exit Function
End if
...
End Function


CODE EXAMPLE 2
Function Test() as integer
Dim ReturnVal as integer
ReturnVal = 0
If ??? then
ReturnVal = 1
Goto EndFunc
End if
...
EndFunc:
Test = ReturnVal
End Function
 
J

Jay Freedman

The technical answer is, it *can* be done in several places; that is,
example 1 will work.

The answer from experience is, it *should* be done only in one place, for a
couple of reasons. The main reason is to help prevent bugs, or to ease
debugging when the inevitable happens. This goes together with the general
rule that, except for error-handling, there should be only one exit point
for each sub/function.
 
J

Jonathan West

Jay Freedman said:
The technical answer is, it *can* be done in several places; that is,
example 1 will work.

The answer from experience is, it *should* be done only in one place, for
a
couple of reasons. The main reason is to help prevent bugs, or to ease
debugging when the inevitable happens. This goes together with the general
rule that, except for error-handling, there should be only one exit point
for each sub/function.

Personally, I take a more relaxed view of this. I think that Example 1 is
perfectly good code, and reduces the amount of jumping about within a
routine and reduces the total number of lines of code.

There are cases where a single exit point would be advisable, such as where
there is a need to restore global parameters (such as the position of the
Selection) prior to exit. These issues need to be addressed on a
case-by-case basis.


--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition www.classicvb.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top