[Gambas-user] Finally/Catch and Return: How is that meant to be used?
benoit.minisini at gambas-basic.org
Thu Sep 14 22:42:03 CEST 2023
Le 14/09/2023 à 19:22, Martin Fischer a écrit :
> Hi Gianluigi,
> for me, it's not about dogma. I'm fine with different languages solving
> problems differently. A C program uses different patterns than a C++
> program or a Python or a Java program.
> My point is that during the evolution of languages some patterns appear
> over and over again. Because there is a need to solve very similar
> problems in these languages!
> Let's take for example the pattern "function". This thing takes
> parameters from the caller, does something and returns something to the
> caller back. This solves the problem of abstracting functionality that
> has to be used at multiple places with only slight variations (the
> parameters). And so on...
> This is such a common problem in programming languages that most of them
> have "functions".
> Now, let's move to the Finally-pattern. This stands for an abstraction
> that allows you to execute a block of code as final operation of a
> function, no matter how this function was left (normal return or
> exception). As such it allows you to clean up resources allocated during
> the function very easily and reliably. Again, this is such a common
> problem that many languages have a means to implement this pattern.
> You might be aware of the old VisualBasic way of solving this problem.
> Yes, you could do it, but it was effort and error-prone. Maybe this is
> the reason why gambas decided to offer a Finally pattern.
> My surprise was just that gambas implements this Finally-abstraction in
> a leaky way. Means: the usual "Finally guaranties that the finally-block
> is executed no matter how you leave the function" does not hold. Instead
> a weaker guarantee is implemented that does not solve the complete
> problem that is normally solved by Finally.
> But: I do not complain. I just want to understand how gambas works.
I understand your point. You could have complained!
I see two reasons why it works like that...
The first one is that I tried to minimize the distance between the
syntax of the language and what is really done by the interpreter.
If I have to make Finally always run when the function exists, it must
be implemented by a subroutine behind the hood, so that it can be called
from any place in the function.
The other reason is lazyness.
In other word, it's not actually such a big deal as every local object
or string is always released at the end of the function, whatever happens.
The problem only comes when you allocate something that must be released
manually. I'm thinking about the Alloc() function and database transactions.
But 99% of the time you are supposed to use Gambas objects or strings,
whose associated ressources are automatically released.
More information about the User