[fpc-pascal] Optional param modifier
Sven Barth
pascaldragon at googlemail.com
Sun Apr 14 19:38:38 CEST 2019
Am 14.04.2019 um 16:05 schrieb Ryan Joseph:
>> On Apr 14, 2019, at 3:15 AM, Sven Barth via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>> Your idea requires exceptions as well. The compiler is not capable checking whether valid entries are passed in at compile time except for simple, constant cases, so runtime checks are needed and the only way to abort something is by exceptions.
> My idea didn’t require the procedure to exit so I don’t see where an exception would be needed. It just says if a param was flagged you would need to check for nil before dereferencing other you get a compile time error.
As already said by Martin: the compiler *can not* determine all cases
whether the parameter is Nil or not, so it *must* be done at runtime to
ensure this. Otherwise the feature is just as useful as this:
=== code begin ===
{$macro on}
{$define optional:=}
procedure Blubb(aArg: TObject optional);
begin
end;
=== code end ===
> I like the idea (because it feels Pascalish) to make a code section that checks requirements but the exit condition is up for debate. I personally wouldn’t use the feature if it meant I need to start the tedious process of wrapping everything in try blocks and taking on what performance costs there are to exceptions (we can’t opt into exceptions via modeswitch so I don’t know what those things are doing and where they are).
As Martin said: this is an error condition like an Assert that should
trigger during development with the default result being a termination
of the application.
> We have custom error systems in our code also so forcing everyone into exceptions would not be nice. I could imagine a bail condition that was jumped to but it would have to be in the code section. That’s usually how we do it now anyways so it shouldn’t be too strange.
>
> function MakeHero (name: string; hp: integer; level: integer): THero;
> require
> name <> ‘’;
> hp > 0;
> (level > 0) and (level < 10);
> begin
> …
> bail
> MyCustomErrorHandler(‘MakeHero() params are invalid’);
> exit(THero.Invalid);
> end;
Invalid contracts are an error that should trigger during development,
but not necessarily when released. So coupling them with the default
exception mechanism is a valid solution.
Regards,
Sven
More information about the fpc-pascal
mailing list