Guidewire ecosystem holds many gems, worth highlighting. On our blog you will find a series of articles which focus on such interesting features authored by Acini Guidewire experts. We will kickstart this journey with a fundamental concept: Null Safety in Gosu.
1. One of the core aspects of null safety in Gosu is the use of the null safe operator, which can be applied to various operations to safeguard your code from unexpected null references. Here are some key uses:
– Null-safe invocation (?.): You can safely invoke methods on nullable objects without causing null pointer exceptions. For example:
𝘥𝘰𝘨?.𝘣𝘢𝘳𝘬𝘴()
– Null-safe default operator (?:): This operator allows you to provide default values when dealing with potentially null variables
𝘷𝘢𝘳 𝘥𝘪𝘴𝘱𝘭𝘢𝘺𝘕𝘢𝘮𝘦 = 𝘥𝘰𝘨.𝘕𝘢𝘮𝘦 ?: "(𝘦𝘮𝘱𝘵𝘺)"
– Null-safe math operators (?*, ?/, ?+, ?-, ?%): Perform mathematical operations on nullable values while gracefully handling null cases:
𝘷𝘢𝘳 𝘱𝘳𝘪𝘤𝘦 = 𝘱𝘳𝘦𝘮𝘪𝘶𝘮 ?* 10
– Null-safe index operator (?[]): Access elements in an array or collection without worrying about null references. However, it does not protect against ArrayIndexOutOfBoundsException:
𝘷𝘢𝘳 𝘥𝘰𝘨 = 𝘥𝘰𝘨𝘴?[𝘪𝘯𝘥𝘦𝘹]
2️. Property access Is NullSafe by default. For instance, this code:
𝘩𝘰𝘶𝘴𝘦?.𝘒𝘪𝘵𝘤𝘩𝘦𝘯?.𝘛𝘢𝘣𝘭𝘦?.𝘈𝘱𝘱𝘭𝘦
is equivalent to:
𝘩𝘰𝘶𝘴𝘦.𝘒𝘪𝘵𝘤𝘩𝘦𝘯.𝘛𝘢𝘣𝘭𝘦.𝘈𝘱𝘱𝘭𝘦
It will work if returned types are reference types.
3. Handling Null Values for Reference and Primitive Types
For reference types, a null safe operation will simply return null if any part of the chain evaluates to null. If the return type of the entire expression is a primitive type (such as int, long, and boolean) than the expression is not null safe. You can fix it by using @ShortCircuitingProperty annotation on property getter or ?. in your access chain than default primitive type value will be returned (int -> 0, boolean -> false).
In specific scenarios, the default values can lead to counterintuitive outcomes. Consider the following examples:
𝘷𝘢𝘳 𝘵𝘦𝘹𝘵: 𝘚𝘵𝘳𝘪𝘯𝘨 = 𝘯𝘶𝘭𝘭
𝘱𝘳𝘪𝘯𝘵(𝘵𝘦𝘹𝘵.𝘌𝘮𝘱𝘵𝘺) // 𝘧𝘢𝘭𝘴𝘦 𝘣𝘶𝘵 𝘦𝘹𝘱𝘦𝘤𝘵𝘦𝘥 𝘳𝘦𝘴𝘶𝘭𝘵 𝘣𝘺 𝘥𝘦𝘷𝘦𝘭𝘰𝘱𝘦𝘳 𝘪𝘴 𝘵𝘳𝘶𝘦
𝘱𝘳𝘪𝘯𝘵(𝘵𝘦𝘹𝘵.𝘉𝘭𝘢𝘯𝘬) // 𝘧𝘢𝘭𝘴𝘦
𝘱𝘳𝘪𝘯𝘵(𝘵𝘦𝘹𝘵.𝘏𝘢𝘴𝘊𝘰𝘯𝘵𝘦𝘯𝘵) // 𝘧𝘢𝘭𝘴𝘦
𝘷𝘢𝘳 𝘢𝘳𝘳𝘢𝘺: 𝘚𝘵𝘳𝘪𝘯𝘨[] = 𝘯𝘶𝘭𝘭
𝘱𝘳𝘪𝘯𝘵(𝘢𝘳𝘳𝘢𝘺.𝘐𝘴𝘌𝘮𝘱𝘵𝘺) // 𝘧𝘢𝘭𝘴𝘦 𝘣𝘶𝘵 𝘦𝘹𝘱𝘦𝘤𝘵𝘦𝘥 𝘳𝘦𝘴𝘶𝘭𝘵 𝘣𝘺 𝘥𝘦𝘷𝘦𝘭𝘰𝘱𝘦𝘳 𝘪𝘴 𝘵𝘳𝘶𝘦
𝘱𝘳𝘪𝘯𝘵(𝘢𝘳𝘳𝘢𝘺.𝘏𝘢𝘴𝘌𝘭𝘦𝘮𝘦𝘯𝘵𝘴) // 𝘯𝘶𝘭𝘭
Null safety in Gosu is a powerful tool to make your code more robust. By mastering these techniques, you can write more reliable software and avoid the pitfalls of null references.