Returning early from a function in classic ASP
Is there a way to return early from a function in classic ASP rather than it run the full length of the function? For example lets say I have the function...
Function MyFunc(str)
if (str = "ReturnNow!") then
Response.Write("What up!")
else
Response.Write("Made it to the end")
end if
End Function
Can I write it like so...
Function MyF开发者_高级运维unc(str)
if (str = "ReturnNow!") then
Response.Write("What up!")
return
end if
Response.Write("Made it to the end")
End Function
Note the return statement which of course I can't do in classic ASP. Is there a way to break code execution where that return statement sits?
Yes using exit function
.
Function MyFunc(str)
if str = "ReturnNow!" then
Response.Write("What up!")
Exit Function
end if
Response.Write("Made it to the end")
End Function
I commonly use this when returning a value from a function.
Function usefulFunc(str)
''# Validate Input
If str = "" Then
usefulFunc = ""
Exit Function
End If
''# Real function
''# ...
End Function
With classic ASP, you need to use Exit Function
:
Function MyFunc(str)
if (str = "ReturnNow!") then
Response.Write("What up!")
Exit Function
end if
Response.Write("Made it to the end")
End Function
As has been pointed out you can use Exit Function
but you should use caution. In the simple example you gave there really is no advantage no other code would have executed
anyway.
Placing exit points throughout a chunk of code can make it hard to follow and debug. More seriously it can lead subsequent changes to the code being harder, requiring more extensive changes and therefore increasing the risk. Hence such a pattern should be considered a "bad smell".
A typical scenario where its reasonably acceptable is where the code may make some assertions on its input parameters before continuing with the body of the code. Other than that you should be able to express a really, really good reason to do it.
You may say "If I do it that way I'll have more If
structures and increase the identation in the code excessively". If that is so then the function has too much code in it anyway and should be refactored into smaller functions.
精彩评论