[fpc-pascal] Optional param modifier

Ryan Joseph ryan at thealchemistguild.com
Fri Apr 12 17:23:55 CEST 2019


I had another idea yesterday while working with Swift and I was curious to hear what anyone thought. In Pascal we have “const”, “constref" “var”, “out” params for functions but no way to document or enforce optional params (which are pointers/classes).

It’s a very common pattern that a function takes a pointer as a parameter and we don’t know if we’re allowed to pass null unless we ready the comment or documentation. I thought there could be an “optional” or “opt” modifier that serves to 1) document the usage of the function and enforce nil checks on the pointer when dereferencing. It’s kind of like “const” for read-only parameters but it says “must-check” instead.

Basically, if a param (or result even?) was marked optional then you would get a compiler error if you tried to dereference the pointer, unless you were in an assigned block (or some other intrinsic since “assigned” is just a function).

What do you think of that? Sounds like an easy way to get some support for nil pointers deref’s and provides self documenting code.

====================

program test;

procedure FreeThis(optional var obj: TObject); 
begin
  // must check assigned or we get a compiler error
  if assigned(obj) then
    begin
      obj.Free;
      obj := nil;
    end;
end;

procedure DoThis(optional obj: TObject); 
begin
  //  must check assigned or we get a compiler error
  if assigned(obj) then
    obj.DoIt;
end;

// can return nil so return value must be checked
function MakeObject: TObject; optional;
begin
  result := TObject.Create;
end;

var
  obj: TObject;
begin

  // MakeObject result is optional so we need to check for assigned
  obj := MakeObject;

  // must check assigned or we get a compiler error when we read the class name
  if assigned(obj) then
    begin
      writeln(‘new object:’, obj.ClassName);
      DoThis(obj);
      FreeThis(obj);
      // "obj" is "optional var" so we get a compiler error unless we check for assigned
      writeln(obj.ClassName);
    end;
end.


Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list