Wish Optional Parameters - clean up the sub, sub1, sub2 mess

rondunn

Member
Licensed User
Longtime User
I'm porting some code from Python, and the biggest pain point so far is the lack of optional parameters.

It is painful for me to have to choose between clumsy parameter lists or multiple versions of the same function, possibly leading to a combinatorial explosion of the same function with different names if there are a number of valid parameter combinations.

Secondly, it makes the standard library look silly. Function(), Function1(), Function2(), with the only differences being an extra parameter thrown in.

An optional parameter could work like this:

sub function_name (p1, p2, optional p3=0)

This means valid calls to the function would be:

function_name (p1, p2)
function_name (p1, p2, p3=99)

Please? A Christmas gift? *smile*
 

JonPM

Well-Known Member
Licensed User
Longtime User
B4X:
Sub function_name(p1 as Int, p2 as Int, p3 as Int)
   If p3 <> -1 then
      param3 = p3
   End If
...
End Sub

function_name(30,25,-1) 'optional parameter ignored
function_name(30,25,20) 'optional parameter used

Not as elegant as having optional params but does the trick
 

rondunn

Member
Licensed User
Longtime User
Not quite. That isn't an optional parameter, it is a parameter with a magic value.

Someone reading the code has to think "What is -1? Is it a real value?" when they read that function.

In my case I've got quite a few functions with 4-6 mandatory parameters, and maybe two optional parameters. Those functions are used in hundreds of places through the application, and only a small number use the optional parameters (that's why they're optional). Very misleading to carry them as mandatory parameters with magic values.

And if you've got a very wide parameter list ... say, 2 mandatory and 10 optional ... that approach gets very tiresome in the calling code.
 

Roycefer

Well-Known Member
Licensed User
Longtime User
You can hack together some optional parameters functionality using Arrays as the parameters.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Or Map:
B4X:
Log(SomeSub(100, "Sdf", CreateMap("ep1": 12)))   
Log(SomeSub(100, "Sdf", CreateMap()))   

Sub SomeSub(Par1 As Int, Par2 As String, ExtraParams As Map)
 Dim ep1 As Int = ExtraParams.GetDefault("ep1", 123)
 Dim ep2 As String = ExtraParams.GetDefault("ep2", "abc")
 Return Par1 + ep1
End Sub
 

rondunn

Member
Licensed User
Longtime User
Thank you for the Map suggestion, that gives me a reasonable alternative.
 
Top