Via TheServerSide.net, I ran across a discussion of how to a discussion of how to do null propagation in C#. What is null propagation? Well, it means that if you evaluate an expression like
a.b().c().d().e()
and if any of the intermediate results is null, the result of the expression is null, without an exception being thrown. Normally, in Java/C#/etc., if (say) "a.b()
" returned null, then "a.b().c()
" would cause an exception when you tried to apply the method "c" to the null value returned by "a.b()
".
Now, in many cases, this is exactly what you want, that your code throws an exception if an attempt is made to apply a method to a null value. So null propagation isn't a general principle that you would want to apply.
However, if you are working with XML, null propagation nicely reproduces the behaviour of XPath queries. If you do an XPath query like
/document/person/address
and there are no "<person>
elements in the document, you get a null result, without any exception being thrown. If would be nice, sometimes, if you use a Java/C#/etc. expression like
document.getPerson().getAddress()
and just get a null result if any of the intermediate results is null. Of course, you could wrap this in one big try/catch block, but
- this makes the code more verbose and unreadable than you would want, since you have to do one try/catch block for every such expression
- exceptions tend to be expensive in code, OK for a few evaluations, but potentially significant for large numbers of evaluations.
How would you add null propagation to a language like Java/C#/etc.? Well, it strikes me there are two ways:
- wrap individual sections of code in some block construct that indicates a part of the code where null propagation should apply
- mark individual classes/methods/properties methods as being "null propagating". This could be done by adding support directly in the language, or it could be done (in Java/C# at least) by adding suitable annotations to the code, and then post-processing the compiled (virtual machine) code to add the necessary extra logic.
I think this would make XML processing code in Java/C# more readable and maintainable. What do you think?