Re: function with multiple returns - Good or Bad idea

  • From: Stefan Knecht <knecht.stefan@xxxxxxxxx>
  • To: backseatdba@xxxxxxxxx
  • Date: Mon, 7 Dec 2015 16:59:54 +0700

I personally like to keep things simple. Adding extra IFs and CASE
statements in the code simply to "return only once" does not make sense to
me personally. I'd have to side with the developer here I think *shudders*
:)

I always try to write code that I could as easily read in 2 years as I can
read it when I'm writing it. Nesting IF's definitely doesn't help with that.

Stefan



On Thu, Dec 3, 2015 at 11:44 PM, Jeff Chirco <backseatdba@xxxxxxxxx> 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: