KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Optional Parameters for Project Methods
PRODUCT: 4D | VERSION: 18 R | PLATFORM: Mac & Win
Published On: January 4, 2021

Some 4D Commands have optional parameters that are not required for the command to run and allow for additional specifications to be applied to the method. For example the String command has two optional parameters, one for the display format of the results and one to specify the time to add onto a date expression.

When creating a project method there are a couple of ways to implement optional parameters.
The primary method is to use conditional checks to see how many paramters were passed into the method, this also applies safe coding with confirming the number of parameters passed.

The number of parameters can be checked with the Count parameters command.

C_TEXT($1;$2)

If(Count parameters<2)
//Only $1 passed
Else
//$2 also passed
End if


If a known potential number of parameters will be passed to the method, the parameters can all be defined like the previous example of declaring $2. However, with a varying number of parameters below are some examples of addressing this.

The first is to use an object. This is the best way to address multiple optional parameters without needing an ordered structure and specific typing of the values passed.

Another way is to use an array or a collection, this will allow varying number of items. Collections may be more complex to handle if implementing mixed types.

Lastly, if the type is known, the sequential parameters style of declaring methods allows the last parameter to be repeated by adding curly braces "{ }" around the number.
For example:
C_LONGINT(${2})
Will create $2, $3, $4, ... $N longint parameters.

Optional parameters can allow methods to be more generic and flexible, but they should be carfully implemented with some of the above stretegies to prevent errors from occurring.