I read an interesting article this morning by Reinier Zwitserloot on the topic of null subtypes in statically typed languages. The issue is that in Java and C# there are a number of different type modifiers for dealing with the concept of nullity. Because of this even a simple base type can be one of three separate somewhat incompatible subtypes.

  1. Can be set to null, can return null.
  2. Can be set to null, returns default value.
  3. Can never be null.

I'm still not sure why we would want or need defaults for nullable types. It seems like a hack used to avoid null reference exceptions when they really should be happening. Perhaps we would all be better served by having all types be nullable and adding some precondition syntactic sugar for method definitions.

If we had two new features, we would be able to kick default and non-nullable types to the curb:

  • Syntactic sugar for null checks. 

As long as the method is not being dynamically invoked, a compiler would be able to infer that the type was not supposed to be null and still throw errors at compile time. As for a dynamic invocation, there would be a type mismatch at call time in any case. There is no need for us as programmers to manage this at a type level. I understand that no one likes writing tons of NullArguementException checks but this is a problem which could be solved in many better ways.

  • Syntactic sugar for parameter defaults.

One of the features I miss most while working in C# is parameter defaults. However, I do understand why they decided to not add it to the language. If a parameter down the list somewhere needs to be set, so do all of it's predecessors. However, it would be possible to use a new keyword (like default) that could be placed where you wanted the default value and this issue could be avoided entirely.

It seems to me though that the reason we need defaults for nullable types is because of the lack of parameter defaults. With the current move towards dynamic types and invocation, it may be necessary to add a little bit of highly optimized reflection so that questions about the nullity of method parameters could be asked easily. However, with parameter defaults and a little bit of highly optimized reflection it would be easy to enforce nullity while avoiding all of these different base subtypes.