Java Needs Properties

OK, this is get­ting ridicu­lous. It’s been, what, 25 years since Java start­ed and we still haven’t fixed one of the sin­gle biggest pain-​points for the language—properties. I mean, just look at this mess:

The amount of boil­er­plate is huge and that’s with­out con­sid­er­ing oth­er boil­er­plate meth­ods like equals():

Ugh, I hate typ­ing all of that. If the object is a bean/​POJO then we can use gen­er­a­tors to help write some of the code at the expense of some weird code: strange inher­i­tance, abstract objects, anno­ta­tions, etc.

Now with prop­er­ties and some com­pil­er mag­ic we could have the same behav­ior that looks more like this:

And this would inter­nal­ly gen­er­ate the sec­ond exam­ple above. If you don’t like adding new key­words we could do it almost as ele­gant­ly with anno­ta­tions:

This could eas­i­ly be extend­ed to sup­port read-​only prop­er­ties as well as over­rid­ing the getter/​setter. Overriding the set­ter is need­ed to val­i­date the val­ue.

This would inter­nal­ly gen­er­ate the equiv­a­lent of this:

Note the assert in the con­struc­tor in the gen­er­at­ed ver­sion. This was added by the @NotNull anno­ta­tion. If the code gen­er­a­tor can guar­an­tee that name is set before the end of the con­struc­tor the it can elide the assert().

Anyway, there is a lot more that can be done. A prop­er­ty could be marked as part of the objec­t’s order­ing and then it would be added to a gen­er­at­ed compareTo() method. The basic idea is to remove the boil­er­plate and to force con­sis­ten­cy in code between pro­gram­mers.

Leave a Reply