Passing arguments by reference - a name dilemma
Posted: 27 May 2011 09:34
This site describes how to create batch functions that isolate their environment from the calling environment. But I see a problem if a variable is passed by reference (ie the name of a variable). More specifically, I see a problem if two or more variables are passed by reference and the function must define local variables.
Example pseudo code 1:
This function fails if either varRef1 or varRef2 is named localVar.
Example pseudo code 2:
This function fails if varRef2 is named arg1.
The tricky problem with this is that functions are supposed to be black boxes. The person calling the function may not remember all of the names of the local variables, so could be unaware of potential problems.
I can't think of a perfect solution to this dilemma. The best I can come up with is to have a convention that all internal variables are prefixed with the function name followed by a dot. If all values to all reference variables are stored in properly named local variables initially, then subsequent local variables can be named anything. At least then a user of the function can have confidence any variable reference can be passed as long as the name does not start with the name of the function. If it does then the function definition should be scanned to make sure there is no name collision. But such name collision is highly unlikely, unless the call is recursive, in which case the caller better know the names of the local variables!
Anyone have any other ideas?
Dave Benham
Example pseudo code 1:
Code: Select all
:foobar varRef1 varRef2
set "localVar=something"
set "%~1=something else"
set "%~2=something else again"
{do whatever and return your result}
exit /b
Example pseudo code 2:
Code: Select all
:foobar varRef1 varRef2
setlocal enableDelayedExpansion
set arg1=!%~1%!
set arg2=!%~2%!
set "localVar=something"
{do whatever and return your result}
exit /b
The tricky problem with this is that functions are supposed to be black boxes. The person calling the function may not remember all of the names of the local variables, so could be unaware of potential problems.
I can't think of a perfect solution to this dilemma. The best I can come up with is to have a convention that all internal variables are prefixed with the function name followed by a dot. If all values to all reference variables are stored in properly named local variables initially, then subsequent local variables can be named anything. At least then a user of the function can have confidence any variable reference can be passed as long as the name does not start with the name of the function. If it does then the function definition should be scanned to make sure there is no name collision. But such name collision is highly unlikely, unless the call is recursive, in which case the caller better know the names of the local variables!
Anyone have any other ideas?
Dave Benham