[Oberon] Multiple RETURN in a procedure

Diego Sardina dsar at eml.cc
Sun Oct 23 09:39:37 CEST 2022


On Sun, Oct 23, 2022, at 6:04 AM, Skulski, Wojciech wrote:
> I know this is a recurring topic, but still... what is so sinister 
> about multiple RETURN statements?

The RETURN statement is effectively a goto that just point to the end of the procedure (ending it prematurely by returning something). In other languages you can use it even in procedures that doesn't return a value.

This leads to a fundamental problem, which you can find in some structured programming books (like Wirth's one, if I remember correctly) or software engineering ones.

The fun fact is that you need GOTO to solve RETURN statement issues :-)

A typical layout of a procedure (especially complex ones) is like the one below:

PROCEDURE Foo (): INTEGER;
BEGIN
  (* Precondintions code *)
  (* Initialization code*)

  [...]

  (* Finalization code *)
  (* Postcondition code *)
  RETURN something
END Foo;

The finalization code and postcondition code must be always reachable and executed, indeed it's at the end of the procedure (and in the first level of indendation).

However with RETURN you can skip that code with unexpected results or less intuitive code path.

This is a typical layout used in languages like C:

PROCEDURE Foo (): INTEGER;
BEGIN
  (* Precondintions code *)
  (* Initialization code*)

  [...]
  (* I guess this is used when no finalization is needed *)
  IF ... THEN RETURN 0; END;
..[...]
  (* We need finalization, let's go there *)
  IF ... THEN GOTO finalize END;
..[...]

  finalize:
  (* Finalization code *)
  (* Postcondition code *)
  RETURN something
END Foo;

So here you must choose:
1) keep RETURN statement and use goto to reach the finalisation code when needed, or
2) get rid of RETURN statement and improve the layout of code.

It's better in my opinion to avoid RETURN statement directly and manage finalization always.

-- 
  Diego Sardina


More information about the Oberon mailing list