Verifying Data Passed to Procedures and Functions
When passing data or "arguments" to parameters in procedures and functions, it is recommended that you verify that the data that procedures and functions receive is as expected. You can use the TYPE( ) and PARAMETERS( ) functions to verify the type and number of arguments passed to procedures and functions.
Verifying Data Type Passed to Parameters
You can use the TYPE( ) function to verify that data passed to parameters has the correct type. In the following example, the function accepts a date value through the parameter dDate
. The function returns a date that is 14 days later than the date that was passed:
FUNCTION plus2weeks( dDate )
PARAMETERS dDate
RETURN dDate + 14
ENDFUNC
The parameter in the function requires a value with Date type. The following version of the function includes code that uses the TYPE( ) function to make sure that the passed value has the correct type:
FUNCTION plus2weeks( dDate )
IF TYPE("dDate") = "D"
RETURN dDate + 14
ELSE
MESSAGEBOX( "Function requires a date value." )
RETURN { - - } && Return an empty date.
ENDIF
ENDFUNC
Verifying the Correct Number of Arguments
When a program passes more arguments than the procedure or function expects, Visual FoxPro generates an error message. When a program passes fewer arguments than the procedure or function expects, the remaining parameters are initialized to False (.F.).
For example, suppose you include two parameters in a procedure definition, but you call the procedure with three arguments, Visual FoxPro generates an error message. However, if you call the procedure with only one argument, the remaining parameter is initialized to False (.F.). However, there is no way to know whether the argument for the last parameter was truly omitted or merely evaluated to .F. Therefore, the following example code uses the PARAMETERS( ) function to check for the appropriate number of arguments:
FUNCTION SaveValue( cStoreTo, cNewVal, lIsInTable )
IF PARAMETERS( ) < 3
MESSAGEBOX( "Too few parameters passed." )
RETURN .F.
ENDIF
IF lIsInTable
REPLACE (cStoreTo) WITH (cNewVal)
ELSE
&cStoreTo = cNewVal
ENDIF
RETURN .T.
ENDFUNC
See Also
Tasks
How to: Create Procedures and Functions
Concepts
Parameters in Procedures and Functions