4

I have a question to ask to which I have not found an explanation for a long time. My teachers keep telling me that return statements in the middle of functions should not be included without ever telling me why. I am mainly referring to the programming languages: C, C++, C# and Java.

The same goes for break statements.

Here is an example of code that is deemed invalid because of the return statement.

void Stack::Extract()
{
    if (Times == 0) 
    {
        cout << "The stack is empty, no number can be drawn" << endl;
        return;
    }

    cout << "Extracted value: " << Vet[Counter-1] << endl;
    Vet[Counter-1] = 0;
    Times--;
    Counter = Times;
}

This is the function for extracting a value from a stack (done via an array), a simple exercise that has been assigned to the class. I'm here asking for information because if return is not to be used in the middle of functions I need to know why.

In this case I have saved the declaration of temporary variables and concatenation of if / else structures as well as preventing the execution of the entire function code if not needed.

EDIT for "Needs details or clarity": I am reading all the comments and I thank you for that. My question is simply what I wrote so in my opinion it doesn't need details or clarity.

Herossandro
  • 131
  • 8
  • 12
    your teachers are ***wrong*** in that they state an _opinion_ for a fact. if your code is clean, there is no reason not to put returns in the middle - or even close to the _beginning_ of your method. clean code _always_ trumps strict rules - especially those without reason. (to freely quote my favourite author, terry pratchett: rules are made so you _think_ about them before you break them) – Franz Gleichmann Feb 01 '22 at 16:35
  • 1
    You're involved in a Holy War, I'm afraid. What they are worried about is if you have a `return` anywhere but the end of the function, the code will be harder to read or more likely to be in error. The goal should be to write code that's easy to read and reason about, and that means the return statement goes where the code is easiest to read and least likely to result in an error, no matter where that is. – user4581301 Feb 01 '22 at 16:37
  • 1
    You often have the case where you need to check some conditions up front and return (possibly with null or an error code) if these preconditions are not met - just like in the example you showed. In my opinion using `if (notReadyToGo) return` at the start is the cleanest way to handle that because it doesn't unnecessarily indent the rest of the code and makes it easier to read. – CherryDT Feb 01 '22 at 16:40
  • 6
    FYI: [Return Early Pattern](https://medium.com/swlh/return-early-pattern-3d18a41bba8) ;-) – Scheff's Cat Feb 01 '22 at 16:40
  • I am newbie to programming. Can returning from a function cause memory wastage? Like if you don't explicitely clean up code before returning, could it cause resource leak? – Aditya Arora Feb 01 '22 at 16:42
  • 1
    In the old days a lot of people wrote long functions rather than splitting them up into separate functions or even entire classes. In a long function, having multiple returns scattered throughout can make the code harder to read. However, short functions don't suffer from this as much - and using early returns for edge cases can make the code much easier to understand. – Matthew Watson Feb 01 '22 at 16:42
  • Tactical note: Don't return something that can be ignored if the program has hit an error condition. The caller expects that a value has been extracted when they call `Stack::Extract`, and if they're not watching the console output they won't know they screwed up. I might throw an exception here to force them to deal with a non-extracting call to `Extract` – user4581301 Feb 01 '22 at 16:42
  • Also see [structured programming](https://en.wikipedia.org/wiki/Structured_programming), particularly the section on "Early Exit". – Matthew Watson Feb 01 '22 at 16:42
  • 1
    This is the [single-entry single-exit](https://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point) doctrine. It elevates purity over practicality. – Pete Becker Feb 01 '22 at 16:43
  • Tactical note: The cure to not cleaning up after an early return: [Resource Acquisition Is Initialization](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) – user4581301 Feb 01 '22 at 16:43
  • 3
    Historically speaking there are a couple of reasons for not doing this which are not nearly as important as they used to be. In older compilers which were not good at optimizing, it could affect optimizations. Also in older code where someone might have allocated memory with new into a raw pointer, another developer coming along and throwing a return in the middle of the function without realizing it might cause a memory leak. These days now that everybody uses RAII and smart pointers and other things that save you from yourself this is less of a danger. – Joe Feb 01 '22 at 16:44
  • @Aditya Arora, No, or at least not any more than a trailing `return`. – ikegami Feb 01 '22 at 16:44
  • As Martin Fowler says: "If the method is clearer with one exit point, use one exit point; otherwise don’t". – Matthew Watson Feb 01 '22 at 16:44
  • 2
    Voted to reopen. It's not that the question isn't clear; it should be closed as a duplicate, with a link. – Pete Becker Feb 01 '22 at 16:44
  • 1
    Apologies RAII only applies to C++, not Java. But in Java you have automatic garbage collection, finally blocks and other fun toys the fill similar purposes. – user4581301 Feb 01 '22 at 16:48
  • 4
    I know it's hard to believe, but your teacher may never have actually written production code. – Dave Doknjas Feb 01 '22 at 16:49
  • 2
    Placing a `return` in the middle or sprinkled throughout the function is often used for efficiency. For example, if early parameter checking results in an error, there's no reason to continue. If you use the nested "if" solution, you may find yourself going way deep just to avoid a return statement. – Thomas Matthews Feb 01 '22 at 16:59
  • From MISRA C-2004, Rule 14.7 (required): A function shall have a single point of exit at the end of the function. *Reasoning:* This is required by IEC 61508, under good programming style. – Thomas Matthews Feb 01 '22 at 17:03
  • 2
    @ThomasMatthews — interesting — but not everyone agrees with everything that MISRA mandates. And MISRA officially only legislates for a restricted subset of C programming. – Jonathan Leffler Feb 01 '22 at 17:27
  • 4
    The 'classic' example would be a complex search algorithm - once a match is found, a return with the result is an obvious and clear approach, rather than some mess of breaks and 'found' flags. – Martin James Feb 01 '22 at 17:32
  • Thank you very much for your answers – Herossandro Feb 01 '22 at 21:57

1 Answers1

10

Having returns inside your functions makes life much easier.

if (x == 0) return;
do other stuff..

Code gets much more readability. I guess, your teacher has a weird approach to this point. My tipp: Follow his rules, as long as you have to. Afterwards do it like 99% of the industry.

patpatwithhat
  • 335
  • 2
  • 11
  • 5
    If the teacher had actually spent any time writing code, they would follow the rule that 99% use: "when you know you're done, get out of the method". – Dave Doknjas Feb 01 '22 at 16:52