RE: function with multiple returns - Good or Bad idea

From: Jeff Smith <jeff.d.smith_at_oracle.com>
Date: Thu, 3 Dec 2015 08:50:21 -0800 (PST)
Message-ID: <df037317-8d85-45c0-8952-7e1284e073dc_at_default>



I think it depends on how many GOTOs they’re using.

 

Sorry, I couldn’t resist.

 

From: Jeff Chirco [mailto:backseatdba_at_gmail.com] Sent: Thursday, December 03, 2015 11:45 AM To: oracle-l_at_freelists.org
Subject: function with multiple returns - Good or Bad idea

 

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.

 

--
http://www.freelists.org/webpage/oracle-l
Received on Thu Dec 03 2015 - 17:50:21 CET

Original text of this message