[fpc-pascal] Optional param modifier

Ryan Joseph ryan at thealchemistguild.com
Sat Apr 13 18:02:10 CEST 2019


> On Apr 13, 2019, at 11:37 AM, Anthony Walter <sysrpl at gmail.com> wrote:
> 
> What's wrong with ...
> 
> procedure FreeThis; overload;
> begin
> end;
> 
> procedure FreeThis(var obj: TObject); overload;
> begin
> end;
> 
> There, now you have an optional argument with a var reference.
> 

Maybe my example wasn’t very clear. Here’s a very common example. We have a function that takes params and has a return value all of which can be null. As the programmer we have to read function comments or check for nil just in case because the documents weren’t clear. Doing "if assigned(p) then” out of fear is not very fun and makes for messy code.

{
  creates a new dude
  @param name: name of the dude
  @param items: list of items (optional)
  @param attrs: list of attributes or nil for default attributes
  @return reference to new dude (may be nil)
}
function CreateNewDude(name: string; items: PItemsList; attrs: PAttrList): PDude;

The attribute in the same way const says the value can’t be changed, says “may be optional so you must check”. If you forget to check for nil the compiler gives you an error.

function CreateNewDude(name: string; optional items: PItemsList; optional attrs: PAttrList): PDude; optional;

It’s a minor detail in the same way const is but it adds a little extra information and gives a little extra safety (I don’t like testing for nil out of fear, I want to know forthright). Swift did a massive overblown implementation of this idea which is a nightmare but the basic concept is as sound as “const" is. 

Am I wrong about this not being common? Marco seemed to think so but I encounter this daily in the real world. In fact just yesterday I parsed the IOKit framework (Mac) to Pascal and saw Apple went through great lengths to add null-defined macros that mark params as “nullable” or not. I.e.

typedef void (*IOHIDCallback)(
                                    void * _Nullable        context,
                                    IOReturn                result, 
                                    void * _Nullable        sender);

So how is this not a common occurrence that deserves a solution?


Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list