Java 方法命名约定:getter 太多
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3211162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java method naming conventions: Too many getters
提问by Are Husby
Why do Java method names use the "get" prefix so extensively? At least in my Java programs there are a lot of methods with names starting with the word "get". The percentage of get-methods is suspiciously high. I am starting to feel that the word "get" is losing its meaning because of inflation. It is noise in my code.
为什么 Java 方法名称如此广泛地使用“get”前缀?至少在我的 Java 程序中,有很多名称以“get”开头的方法。get-methods 的百分比高得令人怀疑。我开始觉得“get”这个词因为通货膨胀而失去意义。这是我的代码中的噪音。
I have noticed that there is a different naming convention being used in functional/declarative programming and PL/SQL. The method name simply states what the method returns. Instead of account.getAmount()or Time.getIsoFormattedDateString(Date date)they will use account.amount()and Time.isoFormattedDateString(Date date). This makes perfect sense to me, as the name of the function describes the result of evaluating the method (assuming there are no side effects, which there shouldn't be anyway). The "get" prefix seems superfluous.
我注意到在函数式/声明式编程和 PL/SQL 中使用了不同的命名约定。方法名称只是说明方法返回的内容。而不是account.getAmount()orTime.getIsoFormattedDateString(Date date)他们将使用account.amount()and Time.isoFormattedDateString(Date date)。这对我来说很有意义,因为函数的名称描述了评估方法的结果(假设没有副作用,无论如何都不应该有)。“get”前缀似乎是多余的。
I have just started reading the book "Clean Code". It says that methods should do only one thing, and that that thing should normally be one of the following:
我刚刚开始阅读《清洁代码》这本书。它说方法应该只做一件事,那件事通常应该是以下之一:
- Notify some object about an event, typically passing the event as a parameter.
- Ask a question about some object, typically with the method name forming a natural language statement, passing the object as parameter and returning a boolean.
- Fetch something, possibly passing some lookup key or some object to be converted as parameter and always returning the desired object/value.
- 将事件通知某个对象,通常将事件作为参数传递。
- 问一个关于某个对象的问题,通常用方法名称形成一个自然语言语句,将对象作为参数传递并返回一个布尔值。
- 获取一些东西,可能传递一些查找键或一些要转换为参数的对象,并始终返回所需的对象/值。
My question is about the third category. Are there naming conventions other than "get" for this kind of methods? What criteria do you use when choosing method names/prefixes?
我的问题是关于第三类。对于这种方法,除了“get”之外还有其他命名约定吗?您在选择方法名称/前缀时使用什么标准?
Here is an example:
下面是一个例子:
I have a class with two methods getDates()and getSpecialDates(). getDates()simply returns the value of a private variable (the reference to a collection of dates). This is a standard getter, as I understand it. getSpecialDates()is different; it calls getDates(), fetches a filter from another class, applies the filter and returns what is effectively a subset of getDates().
我有一个包含两种方法getDates()和getSpecialDates(). getDates()简单地返回私有变量的值(对日期集合的引用)。据我所知,这是一个标准的吸气剂。getSpecialDates()是不同的; 它调用getDates(),从另一个类中获取过滤器,应用过滤器并返回实际上是getDates().
The method getSpecialDates() could be named computeSpecialDates(), findSpecialDates(), selectSpecialDates()or elicitSpecialDates()or whatever. Or I could simply name it specialDates(). And then, for consistency, I could rename getDates()into dates().
该方法getSpecialDates()可以被命名为computeSpecialDates(),findSpecialDates(),selectSpecialDates()或elicitSpecialDates()或什么的。或者我可以简单地命名它specialDates()。然后,为了一致性,我可以重命名getDates()为dates().
Why bother separating between methods that should be prefixed with "get" and methods that should not, and why bother finding replacement words for "get"?
为什么要在应该以“get”为前缀的方法和不应该以“get”为前缀的方法之间进行区分,为什么还要为“get”寻找替换词呢?
回答by Jean-Philippe Caruana
I personally don't usegetters and setters whenever it's possible (meaning : I don't use any framework who needs it, like Struts for instance).
我个人尽可能不使用getter 和 setter(意思是:我不使用任何需要它的框架,例如 Struts)。
I prefer writing immutableobjects (public finalfields) when possible, otherwise I just use public fields : less boiler plate code, more productivity, less side effects. The original justification for get/set is encapsulation (make your objects as shy as possible), but in fact, I don't need it very often.
我更喜欢在可能的情况下编写不可变对象(公共最终字段),否则我只使用公共字段:更少的样板代码、更高的生产力、更少的副作用。get/set 的最初理由是封装(让你的对象尽可能害羞),但实际上,我并不经常需要它。
In Effective Java, Joshua Bloch makes this compelling recommendation :
在Effective Java 中,Joshua Bloch 提出了这个引人注目的建议:
Classes should be immutable unless there's a very good reason to make them mutable... If a class cannot be made immutable, limit its mutability as much as possible.
类应该是不可变的,除非有很好的理由让它们可变......如果一个类不能成为不可变的,尽可能地限制它的可变性。
In the same book, he also says (but I don't want to copy the whole book here) :
在同一本书中,他还说(但我不想在这里复制整本书):
The JavaBeans pattern has serious disadvantages.
JavaBeans 模式有严重的缺点。
I totally aggre with that, since JavaBeans were originally intended for a very narrow problem domain : manipulation of graphical components in an IDE. It is a bad practice to use one solution designed for solving another problem.
我完全同意这一点,因为 JavaBeans 最初是为一个非常狭窄的问题领域设计的:在 IDE 中操作图形组件。使用一个专为解决另一个问题而设计的解决方案是一种不好的做法。
回答by John Topley
It comes from the JavaBeans naming conventions.
它来自JavaBeans 命名约定。
回答by cHao
Part of the reason there's so many get* methods is that Java doesn't support "properties" a la .net/COM, and Java beans and such use functions getX and setX to replicate the functionality of a property called X. Some IDEs for Java take advantage of this to allow the setting and retrieval of properties.
有这么多 get* 方法的部分原因是 Java 不支持 .net/COM 的“属性”,而 Java bean 和此类使用函数 getX 和 setX 来复制名为 X 的属性的功能。一些 IDE 用于Java 利用这一点来允许设置和检索属性。
回答by Jesper
One of the reasons that getter and setter methods are often written in Java is because of the use of JavaBeansconventions.
getter 和 setter 方法通常用 Java 编写的原因之一是因为使用了JavaBeans约定。
The standard Java API isn't consistent itself with regard to this, however. For example, class Stringhas a length()method and interface Collectiondefines a size()method, instead of getLength()or getSize().
然而,标准 Java API 本身并不一致。例如,类String有一个length()方法,接口Collection定义了一个size()方法,而不是getLength()or getSize()。
Java doesn't support the uniform access principle, so you have to write getter and setter methods to access properties.
Java 不支持统一访问原则,因此您必须编写 getter 和 setter 方法来访问属性。
回答by user223364
Method names like getSpecialDates(), computeSpecialDates(), findSpecialDates(), selectSpecialDates()and elicitSpecialDates(), to me are commands because of the use of verbs (actions) in their names. Commands are meant to have side effects everytime you call them. Whereas method names like date(), dates(), specialDates()[nouns] are methods that return a useful value with no side effects. Calling the method multiple times returns the same value everytime, unless a command is called whose side effect is to change state.
像getSpecialDates(), computeSpecialDates(), findSpecialDates(),selectSpecialDates()和elicitSpecialDates(), 之类的方法名称对我来说是命令,因为它们的名称中使用了动词(动作)。每次调用命令时都会产生副作用。而像date(), dates(), specialDates()[名词]这样的方法名称是返回有用值且没有副作用的方法。多次调用该方法每次都会返回相同的值,除非调用的命令的副作用是改变状态。
回答by b_erb
One reason is that it is an essential part of the Java Bean Spec.
一个原因是它是Java Bean Spec的重要组成部分。
回答by Vadim Fedorov
One of reasons that require Java developers to use common get/set convention is that many frameworks rely on it for bean creation and setting the fields. For example, if you have some property configured for Spring bean like <property name="foo" value="bar" />and there's no method named setFoo()in the class, you'll get an error on bean creation.
要求 Java 开发人员使用通用 get/set 约定的原因之一是许多框架依赖它来创建 bean 和设置字段。例如,如果您为 Spring bean 配置了一些属性,并且类中<property name="foo" value="bar" />没有命名方法setFoo(),那么您将在创建 bean 时遇到错误。
回答by Are Husby
Premise 1: A method should do only one thing. Premise 2: A getter method - wether it uses the get prefix or not - should have no side effects. Given these two premises I propose: A method whose role is to fetch something and that does so in a relatively simple an inexpensive manner need not have a verb in its's name.
前提 1:一个方法应该只做一件事。前提 2:getter 方法 - 无论是否使用 get 前缀 - 应该没有副作用。鉴于这两个前提,我建议:一种方法的作用是获取某些东西,并且以相对简单且廉价的方式进行,其名称中不需要动词。
The raison d'etre of a getter is not do something but to evaluate to something. We are not interested in what the method does. Since it has no side effects, whatever computation goes on in the method cannot be of any interest. We are only interested in what the method returns. The method name should reflect that in the form of a noun. Method names consisting only of nouns should always be "getters".
getter 存在的理由不是做某事,而是评估某事。我们对该方法的作用不感兴趣。由于它没有副作用,因此该方法中进行的任何计算都没有任何意义。我们只对方法返回的内容感兴趣。方法名称应该以名词的形式反映出来。仅由名词组成的方法名称应始终为“getter”。
The information in the prefix "get" can be inferred from the lack of verbs. This is simpler and more intuitive than using the get prefix.
前缀“get”中的信息可以从动词的缺乏中推断出来。这比使用 get 前缀更简单、更直观。
A method whose name consists of only a noun and has a return value can be assumed to have no side effects and to be relatively cheap. A method whose name contains a verb and does not have a return value exists to have side effects. A method whose name contains a verb and has a return value can be assumed to be relatively expensive and may have side effects.
可以假定名称仅由名词组成并具有返回值的方法没有副作用并且相对便宜。名称包含动词且没有返回值的方法存在会产生副作用。名称包含动词并具有返回值的方法可以被认为是相对昂贵的并且可能有副作用。
It seems the reason everybody is writing "get" all over the place is merely dogmatic tradition originating from the JavaBeans pattern. Leave the get prefix for when you actually plan to use tools/frameworks that need it!
似乎每个人都到处写“get”的原因仅仅是源自 JavaBeans 模式的教条传统。当您实际计划使用需要它的工具/框架时,请保留 get 前缀!
回答by duffymo
What does "get" matter when we live in a day and age where any IDE that's worth having will generate getters and setters for your private variables and lets you fold them up if you'd rather not read them?
当我们生活在这样一个时代,任何值得拥有的 IDE 都会为您的私有变量生成 getter 和 setter 并允许您将它们折叠起来(如果您不想阅读它们)时,“get”有什么关系?
Your real issue should be about design: Why do your objects have so many attributes? If your objects have nothing but getters and setters, are you suffering from an "anemic domain model"?
你真正的问题应该是关于设计:为什么你的对象有这么多属性?如果您的对象只有 getter 和 setter,那么您是否正在遭受“贫血领域模型”的困扰?
The C# {get, set}notation is marginally better, because it cuts down on the lines of code, but you still have that pesky "get" to type for every variable.
C#{get, set}表示法稍微好一些,因为它减少了代码行数,但是您仍然需要为每个变量键入令人讨厌的“get”。
回答by Tarski
As many people have already stated, get..() and set()... are part of the Java Beans Convention. This is necessary for interoperation with other parts of the Java Spec. For example, in JSP you can access members from a Java been by specifying the property name without the getprefix.
正如许多人已经说过的那样,get..() 和 set()... 是 Java Beans 公约的一部分。这对于与 Java 规范的其他部分进行互操作是必要的。例如,在 JSP 中,您可以通过指定不带get前缀的属性名称来访问来自 Java 的成员。
Given the bean:-
鉴于豆:-
public class Foo {
public int getX() { return 1; }
}
We can do the following JSP to get X: -
我们可以执行以下 JSP 来获取 X:-
<jsp:useBean id="aFoo" class="Foo" />
<c:out value="${aFoo.X}" />
Are there naming conventions other than "get" for this kind of methods?
对于这种方法,除了“get”之外还有其他命名约定吗?
Yes you can use isinstead of getfor boolean properties.
是的,您可以使用is代替get布尔属性。

