Named/optional parameters in Delphi?

Wouter van Nifterick picture Wouter van Nifterick · May 20, 2009 · Viewed 12.9k times · Source

In one of the Delphi demo applications, I've stumbled upon some syntax that I didn't know the Delphi compiler accepted:

// ......\Demos\DelphiWin32\VCLWin32\ActiveX\OleAuto\SrvComp\Word\    
// Main.pas, line 109

Docs.Add(NewTemplate := True); // note the assignment

I can't seem to reproduce this type of parameter passing in my own code, and I never see anyone use it. So these are my questions:

  • Can i use this in "normal" methods and is it part of "the Delphi Language", or is this some compiler hack for automation objects?

  • What's needed in order to be able to use this?

  • Is this anything like C#4's named and optional parameters?


Additional information: I usually pass records or simple classes when there are many optional parameters to methods, but it looks like I wouldn't need that with this syntax. I'm aware of default parameter values, but their usefulness is limited because you cannot provide any parameters to the right of an omitted one. In JavaScript I'm using this named parameter style all the time (be it with different syntax), and it's powerful.

Answer

Rob Kennedy picture Rob Kennedy · May 20, 2009

Clearly the Delphi language supports named parameters since they appear right there in sample Delphi code. Delphi supports named parameters on automation objects, which are objects that implement the IDispatch interface. There are restrictions on the types the parameters and return types can have; in particular, they can't be Delphi classes.

I don't think the convenience you seek from named parameters would outweigh the performance hit you'd take by having every method call routed through the IDispatch.Invoke method. A call may also need to use GetIDsOfNames first. You don't see this in more code because late binding is usually something people try to avoid. Use early binding whenever possible to avoid the cost of looking up dispatch IDs and indirect method invocations.

Delphi supports optional parameters in non-automation code by allowing default values. You can omit the actual parameters for any parameter with a default value as long as you also omit the actual parameters of all subsequent parameters — the compiler ensures that a function's declaration allows for that.

I think optional parameters are overrated. They save time for the (one) person writing the code, but not for the (many) people reading the code. Whoever's reading it needs to know what the default values will be of any unspecified parameters, so you may as well just provide all the values explicitly anyway.