I received this question last week:
Hi Steven,
Here is a question that I have been pondering for sometime and haven't found a definitive answer to. Perhaps you can shed some light.
When writing a procedure in PL/SQL, I pass it all the variables that it needs to do it's job. Of course, it has access to any variables that are defined at the global level - but I rarely if ever use these (perhaps a few constants here and there).
However, if I have a procedure that has a couple nested sub-procedures - should I follow the same pattern as, above? It seems a bit silly to pass parameters to a proc and then re-pass those same parameters to a nested sub-proc when that nested sub-proc already has the variables in scope.
So should the rule of thumb be:
For procedures, pass all parameters in or use local variables as needed. Use global variables only in extraordinary circumstances.
or
For nested sub-procedures, don't pass variables in or out. Use what is already in scope in the outer procedure. Only pass parameters to nested sub-procedures for special situations.
Thanks in advance, Alan
And here is my response:
In an ideal world (looking around my basement office, can't find it), the answer is simple and clear:
Well, except for reality. The reality is that it can be time consuming to extract all out-of-scope references in that new subprogram and convert them into parameters.
So check to see if your editor can help you do that!
But if you do take the time to carefully refactor your code when you created nested subprograms (and you should do both: created nested subprograms and carefully refactor your code), the results will be appreciated by all
The likelihood of you putting a bug into your code as you write drops. And there will be an even steeper decline in the chance of someone coming along later and inadvertently introducing a bug.
In an ideal world (looking around my basement office, can't find it), the answer is simple and clear:
NEVER code out-of-scope references in your subprograms. Use the parameter list to pass in and out any variables that are declared outside that subprogram.There, all done. Nice and neat.
Well, except for reality. The reality is that it can be time consuming to extract all out-of-scope references in that new subprogram and convert them into parameters.
So check to see if your editor can help you do that!
But if you do take the time to carefully refactor your code when you created nested subprograms (and you should do both: created nested subprograms and carefully refactor your code), the results will be appreciated by all
The likelihood of you putting a bug into your code as you write drops. And there will be an even steeper decline in the chance of someone coming along later and inadvertently introducing a bug.