Designing APIs around null-safe property paths

You may want to design your Gosu code logic around the null-safety feature. For example, Gosu uses the java.lang.String class as its native text class. This class includes a built-in method to check whether the String is empty. The method is called isEmpty, and Gosu exposes this method as the Empty property. Use of this property is difficult with Gosu property accessor paths. For example, consider the following if statement:

if (obj.StringProperty.Empty)

Because null coerces implicitly to the type Boolean, which is the type of the Empty property, the expression evaluates to false in either of the following cases:

  • If obj.StringProperty has the value null.
  • The value of StringProperty is non-null but its Empty property evaluates to false.

In typical code, distinguishing between these two very different cases is important. For example, if you need to use the value obj.StringProperty only if the value is non-empty, just checking the value obj.StringProperty.Empty is insufficient.

To work around this restriction, Gosu adds an enhancement property to java.lang.String called HasContent. This property effectively has the reverse of the logic of the Empty property. The HasContent property only returns true if the property has content, so you can use property accessor paths such as the following line:

if (obj.StringProperty.HasContent)

Because null coerces implicitly to the type Boolean, which is the type of the Empty property, the expression evaluates to false in either of the following cases:

  • If obj.StringProperty is null.
  • The String is non-null but the string has no content and so its HasContent property evaluates to false.

These cases are much more similar semantically than the variant that uses Empty (obj.StringProperty.Empty).

Be sure to consider null-safety of property paths as you design your code, particularly with Boolean properties.