Tech Tip: Check object property type before value comparison
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: October 31, 2023
When working with object data types and doing a value comparison on a property, it is a good idea to verify the type before doing the value comparison. In the example below, “myMethod” checks if an input object’s “foo” property is “bar”:
// myMethod #DECLARE($obj : Object) If ($obj.foo="bar") ALERT("Does equal.") Else ALERT("Does not equal.") End if |
If “myMethod” is called with an object that has “foo” assigned to value 1 (integer), an error will be thrown.
$obj:={foo: 1} myMethod($obj) // error |
Instead, wrap the code in a Value type check before proceeding with the value comparison:
// myMethod #DECLARE($obj : Object) If (Value type($obj.foo)=Is text) If ($obj.foo="bar") ALERT("Does equal.") Else ALERT("Does not equal.") End if Else ALERT("Wrong type.") End if |
This way, the error can be caught gracefully.