WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

UDF - UDS Library
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus
plus

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

!! UDFs vs Subroutines !!

 Keywords: GoSub Subroutine User Defined Function UDF  

Question:

I have always used Subroutines and they have not failed me yet but I notice they most of the code examples and in conversation with others I have noticed many developers prefer UDF is there any real difference. I tend to prefer subroutines because the variables are not native to the routine like UDF's but I have used both. Is there a benefit for implementing UDF's within my code and sitting my subroutines on the curb?

Answer:

The main benefit that comes to mind is that a UDFs have its own variable space, with function-level or "local" scope. A user-defined function does not see variables declared in the program (or user-defined function) that called it, so a variable "x" declared in a user-defined function is a different variable than the variable "x" declared in the program above it, and they can each have different values.

In programming circles, the preference is to limit the scope, or visibility, of all variables as much as possible. This is a carefully considered preference, based on long experience with variables that have global scope being accidentally changed by a routine that should never have referred to it. This can happen quite easily, especially with index variables, and the like. Let's say, for example, that your main script defines and use a loop index, iLoopIndex. Now, you define a subroutine, Sub1, which also has a loop index variable, iLoopIndex. Now, inside the loop of Sub1, you call another subroutine, Sub2, which uses the same index variable. I leave the consequences as an exercise for my readers.


Article ID:   W18332
Filename:   !! UDFs vs Subroutines !!.txt
File Created: 2009:07:07:09:02:42
Last Updated: 2009:07:07:09:02:42