When to Use a Function and When to Use a Procedure
Purist argue that a function should return only one value, just as a mathematical function does. This means that a function would take only input parameters and return its only value through the function itself. The function would always be named fo the value it returned, as
sin(),
CustomerID(), and
ScreenHeight() are. A procedure, on the other hand could take input, modify, and output parameters-as many of each as it wanted to.
A common programming practice is to have a function that operates as a procedure and returns a status value. Logically, it works as a procedure, but because it returns a value, it's officially a function. For example, you might have a routine called
FormatOutput() used with a
report object in statements like this one:
Code:
if ( report.FormatOutput( formattedReport ) = Succes ) then ...
In this example,
report.formatOutput() operates as a procedure in that it has an output parameter,
formattedReport, but it is technically a function because the routine itself returns a value. Is this a valid way to use a function? In defense of this approach, you could maintain that the function return value has nothing to do with the main purpose of the routine, formatting output, or with the routine name,
report.FormatOutput(). In that sense it operates more as a procedure does even if it is technically a function. The use of the return value to indicate the success or failure of the procedure is not confusing if the technique is used consistenly.
The alternative is to create a procedure that has a status variable as an explicit paramater, which promotes code like this fragment:
Code:
report.FormatOutput( formattedReport, outputStatus )
if ( outputStatus = Success ) then ...
I prefer the second style style of coding, not because I'm hard-nosed about the difference between functions and procedures but because it makes a clear separation etween the routine call and the test of the status value. To combine the call and the test into one line of code increases the density of the statement and, correspondingly, its complexity. The following use of a function is fine too:
Code:
outputStatus = report.FormatOutput( formattedReport )
if ( outputStatus = Success ) then ...
In short, use a function if the primary purpose of the routine is to return the value indicated by the function name. Otherwise, use a procedure.