Post Java-14 getter/setter naming convention

vbezhenar :

Java 14 introduced records feature. Record creates getter with the same name as field, so one would write print(person.name()) for example. But old Java bean convention dictates that one should name this method as getName().

Using both styles in the same code base does not look very nice. Migrating everything to records is not possible, as they are too limited to replace all use-cases.

Is there any official or semi-official guidelines how to name getters and setters after Java 14 in new code?

Chris T :

Quote from JEP 359:

It is not a goal to declare "war on boilerplate"; in particular, it is not a goal to address the problems of mutable classes using the JavaBean naming conventions.

My understanding, based on the same document is that records are transparent holders for shallowly immutable data.

That being said:

  1. Records are not the place to look for getters/setters syntactical sugar, as they are not meant to replace JavaBeans.
  2. I strongly agree with you that JavaBeans are too verbose. Maybe an additional feature (called beans instead of records) could be implemented - very similar behavior with the records feature but that would permit mutability. In that case, records and beans would not be mutually exclusive.
  3. As it has been mentioned, records are in preview mode. Let's see what the feedback from community would be.

All in all, IMHO they are a step forward... I wrote this example set where you can see a code reduction to ~15% LOC from standard JavaBeans.

Also, note that records behave like normal classes: they can be declared top level or nested, they can be generic, they can implement interfaces (from the same document). You can actually partly simulate JavaBeans (only getters would make sense, though) by extracting an interface containing the getters - however that would be a lot of work and not a really clean solution...

So, based on the logic above, to address your question, no - I didn't see any (semi)official guideline for getters and setters and I don't think that there is a motivation for it right now because, again, records are not a replacement for JavaBeans...

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415359&siteId=1