Re: function with multiple returns - Good or Bad idea

  • From: raza siddiqui <raza.siddiqui@xxxxxxxxxx>
  • To: backseatdba@xxxxxxxxx, "oracle-l@xxxxxxxxxxxxx" <oracle-l@xxxxxxxxxxxxx>
  • Date: Thu, 03 Dec 2015 08:59:04 -0800

True definition of a function is a "subroutine" that must return a value. So a piece of code that executes a desired test etc and returns TRUE / FALSE, a computed VALUE- period. If you have another test, call a different function.

This is the basis of good MODULAR design, rather than having serially-written code..which would be horrendous and inefficient to maintain.

Of course everybody has a choice which option they'd like to use 8-)

Raza

On 12/3/2015 8:44 AM, Jeff Chirco wrote:

So I have recently had a little argument with some developers about allowing multiple return statements inside a function. I am of the opinion that a function should be treated like a funnel with only a single return statement at the bottom of the code, or any returns in a exception block is ok. The idea is to have no random exit points in your code and that everything should exit at the same spot. This make things easier to read and debug.

He has code like this:
/IF l_value1 = 0 THEN
/
/ RETURN 0;
/
/END IF;
/

Bunch of other code
...
...
...
...
...
/IF l_value2 = 0 THEN
/
/ RETURN 0;
/
/END IF;

...
...
...

/
/RETURN l_value;

/
/END;
/

He is of the opinion having a single return requires extra lines of code, extra IF blocks, extra variables, or extra code makes your code more difficult to follow. He believes it is more expressive to "return fast". If you know the result early then return it. He is afraid that if you let the code continue you run the risk of the value being changed. Which I said not if you have your IF or CASE set up correctly.

I also gave him an out with the multiple returns. I said he could create a custom exception, raise it and then handle at the bottom and return 0. He didn't have a comment on that.
For Example:
/declare
/
/ quick_return EXCEPTION;
/
/begin
/
/ IF l_value1 = 0 THEN
/
/ raise quick_return;
/
/END IF;

/
/EXCEPTION
/
/ WHEN quick_return then
/
/ RETURN 0;
/
/END;

/

What do you think? Am I in the wrong here believing that there should only be a single return? Please share your thoughts.


Other related posts: