Recent

Author Topic: [SOLVED] Is there a best method for returning a function value?  (Read 22341 times)

Zoran

  • Hero Member
  • *****
  • Posts: 1988
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Is there a best method for returning a function value?
« Reply #15 on: April 13, 2020, 12:53:41 pm »
I believe in Object Pascal goto (if enabled, you can turn it off easily) only jumps within the current scope. You cannot use it to jump out of a procedure, for instance, or to jump between nested routines.

It's a new "feature":  ;)
https://wiki.freepascal.org/FPC_New_Features_2.6.0#Support_for_non-local_goto.27s
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

440bx

  • Hero Member
  • *****
  • Posts: 6542
Re: Is there a best method for returning a function value?
« Reply #16 on: April 13, 2020, 12:59:23 pm »
I never use continue.
I have no problem using "continue", its target is obvious and already known since it jumps to top of the loop which the programmer already read and, is usually only a few instructions away.

I never use "goto".  If I find myself needing a "goto", I redesign the code.  I consider it an indicator of an unacceptable design flaw in the algorithm.  There is _always_ a cleaner, simpler and easier to understand algorithm that does _not_ need the use of a goto statement.  The problem is, it isn't always obvious.

The worst kind of "goto" there is are exceptions.  Their target address can often only be determined at run time.  Programmers routinely use them to "goto" across stack frames.  That's the worst kind of spaghetti code, yet, for some reason a significant percentage of programmers today consider them acceptable, even "kewl".  And that doesn't even take into account their very significant overhead in terms of time and memory space.  Exceptions, if and when used, should _never_ go across stack frames and, should be used only when dealing with some program resource that is not under the program's control.  In any other case, they are a "bad design" neon sign the size of Texas.


ETA: @howardpc

I believe you are correct.  I don't really know, I don't use those things.
« Last Edit: April 13, 2020, 01:01:22 pm by 440bx »
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

munair

  • Hero Member
  • *****
  • Posts: 887
  • compiler developer @SharpBASIC
    • SharpBASIC
Re: Is there a best method for returning a function value?
« Reply #17 on: April 13, 2020, 01:08:40 pm »
As I said:
Quote
... the only non-trivial difference being it limited to the function body

which is analogous to the current scope.
It's only logical.

flowCRANE

  • Hero Member
  • *****
  • Posts: 986
Re: Is there a best method for returning a function value?
« Reply #18 on: April 13, 2020, 01:12:06 pm »
I never use the function name to assign a return value — this technique is ancient (when there was no support for the hidden Result variable) and not very readable. I always use either Result or Exit, depending on whether I need to leave the function right away or not.

Besides, I never use an additional variable just to rewrite its value to Result at the end of the function — it makes no sense since the Result is a variable, ready to use.

Few examples — return the value specified in one instruction:

Code: Pascal  [Select][+][-]
  1. function Foo(A, B: Integer): Integer;
  2. begin
  3.   A := Max(A, 0);
  4.   B := Min(B, 9);
  5.  
  6.   Result := A * B; // below are no instructions, so Exit is redundant
  7. end;

Using the Result variable to prepare the result in a few steps:

Code: Pascal  [Select][+][-]
  1. function Baz(ANumbers: array of Integer): String;
  2. var
  3.   Number
  4. begin
  5.   Result := 'Funny string: "'; // setting the prefix
  6.  
  7.   for Number in ANumbers do // appending
  8.     Result += Number.ToString();
  9.  
  10.   Result += '"'; // finalizing
  11. end;

And practical example of Exit usability:

Code: Pascal  [Select][+][-]
  1. function Bar(AValue: Integer; ANumbers: array of Integer): Integer;
  2. var
  3.   Index: Integer;
  4. begin
  5.   for Index := Low(ANumbers) to High(ANumbers) do
  6.     if AValue = ANumbers[Index] then
  7.       Exit(Index); // set index as result and exit
  8.  
  9.   Result := -1; // return default index
  10. end;
« Last Edit: April 15, 2020, 11:34:17 am by furious programming »
Lazarus 4.6 with FPC 3.2.2, Windows 11 — all 64-bit

Working solo on a top-down retro-style action/adventure game (pixel art), programming the engine from scratch, using Free Pascal and SDL3.

munair

  • Hero Member
  • *****
  • Posts: 887
  • compiler developer @SharpBASIC
    • SharpBASIC
Re: Is there a best method for returning a function value?
« Reply #19 on: April 13, 2020, 01:12:32 pm »
I do not understand the allergy to the 'goto' concept. The exit(value) statement is exactly the same as
Code: FreeBasic  [Select][+][-]
  1. value = something;
  2. goto end_of_scope;

Totally legit code... We use different words these days, but the principle is still the same, just as 'clean'.
« Last Edit: April 13, 2020, 01:14:54 pm by Munair »
It's only logical.

Bart

  • Hero Member
  • *****
  • Posts: 5731
    • Bart en Mariska's Webstek

440bx

  • Hero Member
  • *****
  • Posts: 6542
Re: Is there a best method for returning a function value?
« Reply #21 on: April 13, 2020, 01:39:48 pm »
I do not understand the allergy to the 'goto' concept. The exit(value) statement is exactly the same as
Totally legit code... We use different words these days, but the principle is still the same, just as 'clean'.
You mentioned the problem with the "goto" statement.  Depending on the language a "goto" may or may not be restricted to the current scope.  If it isn't restricted to the current scope then it may be a strand of spaghetti and, that its inherent problem, it opens the door to spaghetti code.

All that said, I can understand having to use "goto" in a language that does not support "exit"/"continue"/"break", etc but, I consider languages that don't support those instructions to be deficient and, quite often, they are deficient in other ways too, which means that as far as a computer language, they are nothing more than "curiosities' not software development tools.
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

Zoran

  • Hero Member
  • *****
  • Posts: 1988
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Is there a best method for returning a function value?
« Reply #22 on: April 13, 2020, 02:15:04 pm »

ETA: @howardpc

I believe you are correct.  I don't really know, I don't use those things.

As I said, we have this new "feature". :D
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

PascalDragon

  • Hero Member
  • *****
  • Posts: 6398
  • Compiler Developer
Re: Is there a best method for returning a function value?
« Reply #23 on: April 13, 2020, 02:40:25 pm »
The thought of exit(value); being synonymous with a 'goto' statement just about makes my skin curl up... LOL

That's what it is in most languages that provide stack cleanup. You might have multiple locations in your code where you call Exit(xyz); or return xyz;, but the compiler will put the cleanup code in only once (especially if it's more than just ret) and then jump to that location. To be fair nearly anything is a goto at the assembly level, be it a if or a loop... So why should you take exception to Exit(xyz); being such as well?

So, while I am still just getting to know fp, it looks like I might go with 'result :='

The real use of Exit(xyz); is when you know that you want to leave the function scope and are not at the end of the routine, because before Exit(xyz); was introduced you had to use Result := xyz; Exit;.

jwdietrich

  • Hero Member
  • *****
  • Posts: 1278
    • formatio reticularis
Re: Is there a best method for returning a function value?
« Reply #24 on: April 13, 2020, 03:18:56 pm »
The Goto, Spaghetti and the Velociraptor

Bart

Great. I like the idea of seeing "programming as logical poetry".
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 4.2.0 | FPC 3.2.2 | PPC, Intel, ARM | macOS, Windows, Linux

GypsyPrince

  • Guest
Re: Is there a best method for returning a function value?
« Reply #25 on: April 13, 2020, 06:28:22 pm »
For purely academic conversation...

one reason the 'Goto' garbage was so prevalent in BASIC languages was the use of structured error handling.

All routines return an error value upon execution. If the routine is successful, 0 is returned. Unfortunately, when using structured error handling, the 'Goto' statement didn't bother to check for a value of zero and cancel itself. Hence, even upon successful execution of the routine, the error handler label would get executed, requiring the use of the Exit Sub() statement to prevent it, or the second option of testing for 0.

I. VBA/VB6
Code: Pascal  [Select][+][-]
  1. Private Sub MyProcedure(ByVal MyParam As Type)
  2.     On Error GoTo ErrHndlr
  3.  
  4.     <Do Something>
  5.  
  6.     Exit Sub //Required to prevent error handler 'Goto' from triggering.
  7.  
  8. ErrHndlr:
  9.     <Handle Error>
  10. End Sub

II. VBA/VB6
Code: Pascal  [Select][+][-]
  1. Private Sub MyProcedure(ByVal MyParam As Type)
  2.     On Error GoTo ErrHndlr
  3.  
  4.     <Do Something>
  5.  
  6. ErrHndlr:
  7.     If Err.Number <> 0 Then  //Required to prevent error handler from triggering.
  8.         <Handle Error>
  9.     End If
  10. End Sub

Thankfully, the Try/Catch/Finally block appears to have eliminated the need to check to see if the returned error code is anything other than zero, and no need to exit the routine before the error handler 'Goto' is executed.
« Last Edit: April 13, 2020, 08:31:06 pm by GypsyPrince »

jamie

  • Hero Member
  • *****
  • Posts: 7774
Re: Is there a best method for returning a function value?
« Reply #26 on: April 14, 2020, 12:40:04 am »
Code: Pascal  [Select][+][-]
  1. {Live dangerously }
  2. procedure GoTestIt (Out Test);
  3. Begin
  4.   DWORD(Test) := 1;
  5. End;                    
  6.  

 GotTestIt(Anything);

The only true wisdom is knowing you know nothing

jwdietrich

  • Hero Member
  • *****
  • Posts: 1278
    • formatio reticularis
Re: Is there a best method for returning a function value?
« Reply #27 on: April 14, 2020, 09:45:58 am »
Of note, control structures like goto raise security concerns. This is why they are discouraged by guidelines for software security, e.g. The Power of 10.
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 4.2.0 | FPC 3.2.2 | PPC, Intel, ARM | macOS, Windows, Linux

munair

  • Hero Member
  • *****
  • Posts: 887
  • compiler developer @SharpBASIC
    • SharpBASIC
Re: Is there a best method for returning a function value?
« Reply #28 on: April 14, 2020, 10:03:30 am »
Of note, control structures like goto raise security concerns. This is why they are discouraged by guidelines for software security, e.g. The Power of 10.
It reads:
Quote
Avoid complex flow constructs, such as goto, direct or indirect recursion.
Some programming tasks are very difficult to accomplish without recursion.

But I underline this one:
Quote
Limit the use of pointers to a single dereference and avoid using function pointers.

There are some good points in that guideline.

EDIT: Interesting that the motivation for that guideline regarded the C language:
Quote
The Power of 10 Rules was defined in 2006 by Gerard J. Holzmann at the JPL|NASA/JPL Laboratory for Reliable Software. Their main intention is eliminating certain C coding practices which make code difficult to review or statically analyze. These rules have been incorporated into the coding standards of multiple institutions.
« Last Edit: April 14, 2020, 10:13:04 am by Munair »
It's only logical.

jwdietrich

  • Hero Member
  • *****
  • Posts: 1278
    • formatio reticularis
Re: Is there a best method for returning a function value?
« Reply #29 on: April 14, 2020, 01:17:09 pm »
Some programming tasks are very difficult to accomplish without recursion.

Yes. of course, but if a good alternative is at hand then it is better to avoid recursion.
function GetRandomNumber: integer; // xkcd.com
begin
  GetRandomNumber := 4; // chosen by fair dice roll. Guaranteed to be random.
end;

http://www.formatio-reticularis.de

Lazarus 4.2.0 | FPC 3.2.2 | PPC, Intel, ARM | macOS, Windows, Linux

 

TinyPortal © 2005-2018