Tech Tip: Two things to check when writing method that takes collection parameter
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: September 10, 2024
When writing a method or function that takes a collection as a parameter, the collection should generally be checked for a couple things to help avoid errors.
First, does the input collection contain the correct amount of elements? For example, if the method code depends on accessing certain indices in the collection, it could return an “index in collection is out of range” error if the input collection happens to be empty. A basic check on the size of the input collection can help avoid this, for instance:
If ($inputCollection.length>0) // access collection items End if |
Second, do elements in the collection have the correct type? For example, consider the method below:
// myMethod #DECLARE($coll : Collection) : Boolean $sum:=0 For each ($item; $coll) $sum+=$item End for each return $sum>15 |
It takes in a collection and sums up its integers to check if the sum is greater than 15. Simple enough, but what if a collection was passed into the method like below:
$inputColl:=[1; 2; "3"] $result:=myMethod($inputColl) |
Notice that the third item is text type, not integer. Running this will cause an error:
Writing some defensive code here would help protect against potential wrong types. For example, the "For each" block above can be re-written:
For each ($item; $coll) If (Value type($item)=Is real) $sum:=$sum+$item End if End for each |