Faking named parameters

Xojo doesnt support named parameters. And I dont expect they are likely to add it any time soon. But, you can kind of fake it for yourself with a bit of work.

Xojo supports both variadic parameter lists, ones that take an unbounded list of parameter, and a declarative syntax for creating pairs as literals.

You can combine this into faking named parameters.

If you define a method as

Sub foo( paramarray namedParams as Pair )

You can call it like

Foo( "param1":1, "param2":"2" )

and the method will get an array of pairs named namedParams that is composed of pairs. Each pair in the list will, for this example, have its left property holding the name and the right property holding he parameter value.

You can iterate over the array and pull out the relevant values into local variables and the method behaves as if you support “named” parameters like :

dim param1 as integer
dim param2 as integer

for each param as pair in namedParams
  select case true
    case param.left = "param1"
      param1 = param.right.integervalue
    case param.left = "param2"
      param2 = param.right.stringvalue
  else   
     // here ypou cane do whatever you want 
     // but I chose to raise an exception
     Raise new UnsupportedOperationException
  end select
next

You could take this further and add an overload that supports positional parameters like

Sub foo( param1 as integer, param2 as string )

and if you do this you probably want to make sure the named parameter version validates that the types of values for the named versions are consistent with the positional version.

And now you can call with named params or positional params and you can decide whether internally the named one calls into the positional param one or vice versa so you dont have to write the same code twice – just put a different API on it.