On the design of nullable property


#1

Hi all,

I’m now playing around the new Base.getproperty method, which was introduced in the master branch of Julia very recently. It is cool, so I’m planning to use it in my packages.

The question is what will be the best practice for this new feature when the property of an object may be null. For example, assuming you write code to represent a tree structure consists of Nodes, you would like to add some properties like node.parent or node.nextsibling for traversal. However, these properties may be undefined when the node is a root node or the last sibling. In such a case, I think we can take one of two options:

  1. The return type of Base.getproperty is typed as Node. If you try to access an undefined property, it will throw some exception (e.g. ArgumentError).
  2. The return type of Base.getproperty is typed as Union{Node,Nothing}. If you try to access an undefined property, it will return nothing.

If you choose the first approach, you will need another method to check the existence of the property a priori (e.g. node.hasparent). I think this is cumbersome so I’d like to take the second option. However, I’m not perfectly sure about it because this was supposed to be a bad part due to type instability. Also, the deprecation of cond?foo:bar syntax suggests a new feature is planned on the handling of nullable values.

Do we have a consensus on the interface of nullable properties?


#2

I think the same principles apply whether you do parent(node) or node.parent. So if you threw an error before you should throw one now, etc.


#3

I would definitely go with the second, as long as a Node cannot already have the value nothing.
Note: I’d also use the convention of using Maybe(T) for Union{T, Void}, (I don’t recall which package we picked that one up from), that makes things shorter to write, and IMO easier to read.

Also, since the speed of handling a small Union type is pretty good now, I think it may be faster than
setting up the try handler (because at least currently, Julia try is not zero cost, as in some other languages,
such as CLU).