Java中getter的命名约定有多重要? [英] How important are naming conventions for getters in Java?

查看:83
本文介绍了Java中getter的命名约定有多重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常相信一致性,因此也是惯例。

I’m a huge believer in consistency, and hence conventions.

但是,我目前正在开发一个Java框架,其中包含这些约定(特别是 get / set prefix convention)似乎妨碍了可读性。例如,某些类将具有 id name 属性并使用 o.getId() 而不是 o.id()由于多种原因似乎完全没有意义:

However, I’m currently developing a framework in Java where these conventions (specifically the get/set prefix convention) seem to get in the way of readability. For example, some classes will have id and name properties and using o.getId() instead of o.id() seems utterly pointless for a number of reasons:


  • 这些类是不可变的,所以(通常)没有相应的setter,

  • 没有混淆的可能性,

  • get 在这种情况下不传达其他语义,

  • 我用这个获取 -less在整个库中非常一致地命名模式。

  • The classes are immutable so there will (generally) be no corresponding setter,
  • there is no chance of confusion,
  • the get in this case conveys no additional semantics, and
  • I use this get-less naming schema quite consistently throughout the library.

我从Java 集合类(以及Java平台库中的其他类)也违反了JavaBean约定(例如,它们使用 size 而不是 getSize 等。)。

I am getting some reassurance from the Java Collection classes (and other classes from the Java Platform library) which also violate JavaBean conventions (e.g. they use size instead of getSize etc.).

为了解决这个问题:永远不会使用该组件作为JavaBean,因为它们无法以这种方式有意义地使用。

To get this concern out of the way: the component will never be used as a JavaBean since they cannot be meaningfully used that way.

在其他方面我是不是经验丰富的Java用户,我不知道其他Java开发人员对库的期望。我可以在这里遵循Java平台类的示例,还是被认为是糟糕的风格?在Java库类中违反 get / set 约定是否被认为是一个错误的回顾?或者在不适用时忽略JavaBean约定是完全正常的吗?

On the other hand, I am not a seasoned Java user and I don’t know what other Java developers expect of a library. Can I follow the example of the Java Platform classes in this or is it considered bad style? Is the violation of the get/set convention in Java library classes deemed a mistake in retrospect? Or is it completely normal to ignore the JavaBean conventions when not applicable?

Java的Sun代码约定根本没有提到这一点。)

(The Sun code conventions for Java don’t mention this at all.)

推荐答案

如果您遵循相应的命名约定,那么第三方工具可以轻松地与您的库集成并使用您的库。他们期望 getX() isX()等等,并尝试通过反思找到这些。

If you follow the appropriate naming conventions, then 3rd-party tools can easily integrate with and use your library. They will expect getX(), isX() etc. and try to find these through reflection.

虽然您说这些目前不会作为JavaBeans公开,但我仍然会遵循惯例。谁知道你可能想要进一步做什么?或者在稍后阶段你可能想要提取这个对象的接口并创建一个可以通过其他工具访问的代理?

Although you say that these won't be exposed as JavaBeans currently, I would still follow the conventions. Who knows what you may want to do further down the line ? Or perhaps at a later stage you'll want to extract an interface to this object and create a proxy that can be accessed via other tools ?

这篇关于Java中getter的命名约定有多重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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