Not a bad idea, but here are two and a half alternatives we could consider:

(1) Simply ban use of “this” within a compact constructor.  This might seem like overkill, but it is very easy to explain: the keyword “this” is not available in a compact constructor, period.  Because the argument names shadow the field names, you don’t have access to the fields at all in a compact constructor.  If you don’t like it, write a non-compact constructor.

That's a nice clean way to do it, because under this (heh) model, `this` is useless -- can't read the fields (they're DU), can't write them (cause I say so), shouldn't call instance methods anyway (because the object is uninitilized and therefore may be in an invalid state), and you shouldn't pass `this` to alien code (because that undermines the final field guarantees of the JMM.)  So if its useless, just don't utter it.

(Which, in hindsight, might have been a good rule for _all_ constructors, if there was another way to initialize the fields. Surely would have eliminated much verifier complexity.)

(2) Change the model so that the constructor arguments are committed to the fields _before_ executing the body of a compact constructor, then for each argument and corresponding field use this assignment analysis to possibly take additional action on exit:

if the argument is definitely not assigned in the body of the compact constructor
take no action on exit
else if the corresponding field is definitely not assigned in the body of the compact constructor
assign the argument to its corresponding field on exit
else compile-time error

This rule is intended to allow the programmer to use either style safely.

(2a) Same as (2), but apply it on a bulk basis rather than a per-argument basis:

if all the arguments are definitely not assigned in the body of the compact constructor
take no action on exit
else if all the corresponding fields are definitely not assigned in the body of the compact constructor
assign all the arguments to their corresponding fields on exit
else compile-time error

This rule would further require the programmer to adopt the same style uniformly for all arguments.


All of these suggestions depend on compile-time analysis to eliminate redundant assignments.


We already do this analysis now, but I'm having a bit of buyers remorse on it.

I like (1)!  It is safe and easy to explain.

Reply via email to