Value types, encapsulation, and uninitialized values

Brian Goetz brian.goetz at
Tue Oct 16 00:38:58 UTC 2018

> Given the split, and that LocalDate already has null as a default
> without the world collapsing, this really does seem like a good choice
> for value type authors to make (and may make migration
> easier/clearer). Forcing a default value on classes like Money or
> LocalDate (even if via a constructor) is forcing a logically nonsense
> value to be handled - not very "codes like a class". So I just can't
> see how that option would work. Null already is the concept for
> default "not initialized", so should be the conceptual model to build
> on here.

Yes, this is exactly the problem (and split) I had in mind; that if a class is in the “zero not a reasonable value” category, the burden on the author seems pretty high.  (But its not insurmountable; the code would have to check for the default value on method entry, and throw.  But this is obviously too easy to get wrong, so we want to make this easier.)  

> What I'm keen to avoid is a situation where NonNull values have a much
> better performance model that Nullable ones. ie. a Nullable value type
> should still be able to gain the benefits of flattening, otherwise
> whats the point? (A nullable value type is just a value type where the
> bit-pattern of zero is given a special name and prevented from being
> invoked on. Neither of those things prevent the value from being
> flattened.)

Be careful here what you mean by "performance model.”  Nullable value types WILL be more expensive than non-nullable ones in at least some dimensions.  Remember, value types are a performance win on multiple dimensions:

 - flatness
 - density
 - dispatch (due to monomorphicity)
 - calling convention (scalarizability, non-identity, etc)
 - .. more …

Nullable value types would retain the flatness win; they might retain the density win (but in the worst case, might need more bits, backsliding on that count); the extra code paths required for null checking would likely put a dent in the others.  So the advice would definitely be “use this with care; it has a cost.”  It’s surely not 100% of what you gained by going to values in the first place, but its not 0% either.  Which is a good argument for making the user choose.  

More information about the valhalla-dev mailing list