可访问数据的Java约定. (公共访问者和获取者/命名) [英] Java conventions for accessible data. (Public accessors & Getters/Naming)

查看:86
本文介绍了可访问数据的Java约定. (公共访问者和获取者/命名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过Java API,您会看到无数次发生冲突的命名和做法,这确实让我感到困惑.

Through the Java API you see numerous occurrences of conflicting naming and practices which are really confusing to me.

例如:

String 类具有一个名为count的私有变量(Integer),它可以跟踪字符串的大小,但是,它由一个名为length()的吸气剂返回.

The String class has a private variable (Integer) by the name of count which keeps track of the size of the string, however this is returned by a getter by the name of length().

如果您移至任何类型的数组,而不是使用getter方法来获取长度,则它们只是通过公共访问器传递变量,并且可以通过arrayInstance.length来获取.

If you move over to any type of arrays, instead of having a getter method for length, they just pass the variable through with a public accessor, and it can be obtained through arrayInstance.length.

回到String类,我们有一个String#getBytes()方法,它是一个吸气剂,类似于length()吸气剂,但是执行更多的逻辑来获取和返回值.

Moving back to the String class we have the String#getBytes() method which is a getter, similar to the length() getter, however performs slightly more logic to get and return the value.

对我个人而言,创建带有get前缀的吸气剂似乎是多余的,例如,我宁可键入GamePacket#data()而不是GamePacket#getData(),但是我觉得这种命名背后可能有更深层的含义,而不仅仅是不一致

To me, personally, creating a getter with the prefix of get seems redundant, for example I rather type GamePacket#data() versus GamePacket#getData() however I feel like there may be a deeper meaning behind this naming instead of just inconsistency.

此外,为什么Array[]为什么不为length使用吸气剂?

Also, why doesn't the Array[] use a getter for length?

有人会为我提供一些帮助吗?

Would anybody be kind enough to shed some light on this for me?

推荐答案

字母(和setter)来自Java Bean规范.使用它们的原因有多种:

Getters (and setters) come from the Java Bean specification. The reasons to use them are multiple:

  • 大多数Java开发人员都希望访问器这样命名
  • 遵守这些约定的API更容易发现.例如,在我的IDE中,我经常按get Ctrl Space 来发现对象中所有可用的信息.
  • 许多API和框架都依靠这些约定来工作:JSP EL,MVC框架根据请求参数,JPA,依赖注入框架(例如Spring等)填充bean.
  • most Java developers expect accessors to be named like that
  • an API respecting these conventions is easier to discover. For example, in my IDE, I'll often press get CtrlSpace to discover all the information available in an object.
  • many APIs and frameworks rely on these conventions to work: the JSP EL, MVC frameworks populating beans from request parameters, JPA, dependency injection frameworks like Spring, etc.

通常使用与保存信息的私有变量相同的方式命名getter,但重要的是封装和公共API,因此没有什么可以阻止您在getter中计算值,或者用不同的方式命名私有字段.

You usually name the getter the same way as the private variable that holds the information, but what matters is encapsulation and the public API, so nothing prevents you from computing a value in a getter, or to name the private field a different way.

这篇关于可访问数据的Java约定. (公共访问者和获取者/命名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆