Post Java-14 getter/setter naming convention

三世轮回 提交于 2020-05-08 07:19:02

问题


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?


回答1:


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...



来源:https://stackoverflow.com/questions/59981081/post-java-14-getter-setter-naming-convention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!