Friday 26 August 2011

No Way Out

Question:
My understanding is that a function should send back data only through its return clause. Why does PL/SQL allow us to define OUT parameters with functions? Is there any specific application of this feature?
Answer:
I make the following recommendations for function structure:
• Do not put OUT or IN OUT arguments into the parameter list of a function.
• Return all data in the RETURN clause of the function.
• Code only one RETURN statement in the executable section of the function, and make that RETURN the last line of that section.
• If you need to return multiple pieces of information, either return a composite datatype (record, object, collection, and so on) or change the function to a procedure and then use OUT or IN OUT arguments.
Why does Oracle allow us to put OUT arguments into a function's parameter list? Probably because it recognizes that the world is not black and white but made up of many shades of gray. Programmers are a widely varied lot, with many different code-writing styles.
I am very glad that Oracle did not decide to enforce this best practice of avoiding OUT parameters with functions (which is not, by the way, a universally accepted or adopted practice in the world of programming) in its implementation in PL/SQL.
My understanding of the world of C programming, for example, is that developers commonly write functions that return a status code indicating whether or not the function was successful. They then use OUT arguments in the parameter list to return the information from the function.
I don't like that approach, certainly not in PL/SQL, but I feel we need more language flexibility, not less. And we need to develop our own personal discipline to decide which features of PL/SQL to use and which to leave alone.
Certainly, there can be situations in which a function with an OUT parameter is useful. Consider the following block. The source_code.more_data function returns a Boolean value, which is used to terminate the loop, but also returns as an OUT argument the data structure that is then processed within the loop.
BEGIN
source_code.init (...);

WHILE source_code.more_data
(output_structure)
LOOP
process (output_structure);
END LOOP;

source_code.TERMINATE ();
END;
Now, I could certainly rewrite this code so that it relies on either a function with no OUT parameters or a procedure, but that would make the code more clumsy and difficult to read.
So, we definitely don't want Oracle making such a function with an OUT or IN OUT parameter illegal, but I do think that such a parameter list makes sense only for special-purpose situations.

No comments:

Post a Comment