Java add() 方法约定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3072519/
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 add() method convention
提问by rampion
So, I'm normally a ruby programmer, so my grasp of Java conventions is shaky at best. If I have a class A and want to define a method to add two instances of that class, what's the convention on the behaviour and return type?
所以,我通常是一个 ruby 程序员,所以我对 Java 约定的掌握充其量是不稳定的。如果我有一个类 A 并且想要定义一个方法来添加该类的两个实例,那么行为和返回类型的约定是什么?
public class A
{
    //...
    public NotSureWhatTypeItShouldReturn add (A that) { /* ... */ }
Should I
我是不是该
- return a boolean indicating success and modify the target, or
 - return a modified copy of the target and throw an exception on error
 
- 返回一个布尔值指示成功并修改目标,或
 - 返回目标的修改副本并在出错时抛出异常
 
Which fits with the normal Java convention for this kind of method?
哪个符合这种方法的正常 Java 约定?
回答by Michael Mrozek
Both exist: Collection.addmodifies the collection and returns a boolean, and BigInteger.addreturns a new BigIntegerthat holds the sum of the original and the passed-in instance.
两者都存在:Collection.add修改集合并返回一个布尔值,并BigInteger.add返回一个BigInteger包含原始实例和传入实例总和的新集合。
I generally expect most methods to modify the instance they're being called on, rather than returning a new object of the same type, but if there's a good use case for keeping instances const and returning a new instance all the time you can certainly do that
我通常希望大多数方法修改它们被调用的实例,而不是返回相同类型的新对象,但是如果有一个很好的用例来保持实例常量并始终返回一个新实例,你当然可以这样做那
回答by Jon Skeet
Don't return a boolean unless it's an "expected failure" e.g. trying to add to a set. If something actually goes wrong, throw an exception.
不要返回布尔值,除非它是“预期失败”,例如尝试添加到集合中。如果确实出现问题,则抛出异常。
Now, you couldreturn a modified copy - or you could add to the existing object. Immutability is often a nice property... but most collections in Java are mutable. If you're going down the immutable route you might want to considerusing plusinstead of add- it gives more of a feeling of "there's a result you should look at, and I won't change the target" IMO.
现在,您可以返回修改后的副本 - 或者您可以添加到现有对象。不变性通常是一个很好的属性……但是 Java 中的大多数集合都是可变的。如果您要沿着不可变的路线走下去,您可能需要考虑使用plus而不是add- 它给人的感觉更多的是“您应该查看结果,而我不会改变目标”IMO。
回答by Lie Ryan
Everyone here is thinking about Collections.add()-type method; but I doubt that's what you're thinking. Are you more in the line of, say, Vector2D.add()which adds the x and y component of the Vector2D together? 
这里的每个人都在考虑 Collections.add() 类型的方法;但我怀疑这就是你的想法。您是否更Vector2D.add()倾向于将 Vector2D 的 x 和 y 分量加在一起?
In Java, as far as I can tell, Collections generally modify themselves (and so does Collections.add).
在 Java 中,据我所知,集合通常会修改自己(Collections.add 也是如此)。
However, non-Collections object (e.g. Vector2D) varies more. Among the conventions I've seen:
但是,非集合对象(例如 Vector2D)变化更大。在我见过的约定中:
Cls add(Cls b)which returns a new object and does not modify existing instancesvoid add(Cls b)which modifiesthisand returns nothing (i.e. returns void), it should not modifyb. There is no point in returningboolsince this type of addition is never supposed to fail (and if it does anyway, an Exception would be appropriate).Cls add(Cls a, Cls b)which returns a new object, modifies neither a nor b. Cls.add() is a static method in Cls class.
Cls add(Cls b)它返回一个新对象并且不修改现有实例void add(Cls b)修改this并返回任何内容(即返回无效),它不应该修改b. 返回是没有意义的,bool因为这种类型的添加永远不会失败(如果它无论如何都会失败,则 Exception 将是合适的)。Cls add(Cls a, Cls b)它返回一个新对象,既不修改 a 也不修改 b。Cls.add() 是 Cls 类中的静态方法。
Personally, I prefer the first style for arithmetic-style add(); precisely because we can do a.add(b).add(c).add(d) which looks a bit like "a + b + c + d". (I wouldn't normally do this if ais a Collection; since serial addition looks weird for Collections object.)
就个人而言,我更喜欢算术式 add(); 的第一种样式。正是因为我们可以做 a.add(b).add(c).add(d) 这看起来有点像“a + b + c + d”。(如果a是 Collection,我通常不会这样做;因为 Collections 对象的串行添加看起来很奇怪。)
回答by stacker
I would recommend the same behaviour as in Collection.add, this is what I would expect.
我会推荐与Collection.add相同的行为,这就是我所期望的。
回答by MikeD
From the Java Collections API:
从 Java集合 API:
Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)
Collections that support this operation may place limitations on what elements may be added to this collection. In particular, some collections will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.
确保此集合包含指定的元素(可选操作)。如果此集合因调用而更改,则返回 true。(如果此集合不允许重复并且已经包含指定的元素,则返回 false。)
支持此操作的集合可能会对可以添加到此集合中的元素设置限制。特别是,一些集合会拒绝添加空元素,而另一些集合会对可能添加的元素类型施加限制。集合类应在其文档中明确指定对可以添加哪些元素的任何限制。
如果集合由于任何原因而拒绝添加特定元素,而不是因为它已经包含该元素,则它必须抛出异常(而不是返回 false)。这保留了在此调用返回后集合始终包含指定元素的不变性。
回答by polygenelubricants
This is not really a convention, but only what boolean Collection<E>.add(E)exemplifies:
这并不是真正的约定,而只是boolean Collection<E>.add(E)举例说明:
Returns:
trueif this collection changed as a result of the call
Throws:UnsupportedOperationException- if theaddoperation is not supported by this collection
返回:
true如果此集合因调用而更改
抛出:UnsupportedOperationException- 如果add此集合不支持该操作
Methods of the Java Collections Framework classes rarely returns the collection that they're invoked upon. That is, it's not idiomatic to support this:
Java Collections Framework 类的方法很少返回调用它们的集合。也就是说,支持这一点并不习惯:
mySet.add(thisThing).add(thatThing).add(thoseAlso);
Some classes in the Java libraries employ the "fluid" style, e.g. Appendablesuch as StringBuilder, but none of the main Java Collections Framework classes do.
在Java库的一些类采用“流体”的风格,如Appendable如StringBuilder,但没有主要的Java集合框架类的事情。
回答by OscarRyz
Depends on the semantic of your class, but typically it would be:
取决于您的类的语义,但通常是:
public void add( A that ) {
} 
If what you intend is just to aggregate elements.
如果您的目的只是聚合元素。
You can use:
您可以使用:
public boolean add( A that ) {
}
If your intention is to know if the structure was modified or not ( Like with a java.util.Setor collections in general ) 
如果您想知道结构是否被修改(就像java.util.Set一般的a或集合)
And you can use public A add( A that ){}if your intention is to create a "builder like" object ( just like StringBuilder.appendmethod. 
public A add( A that ){}如果您的意图是创建“类似构建器”的对象(就像StringBuilder.append方法一样),则可以使用。
 A a = new A();
 a.add( a ).add( b ).add( c ).build();
So depending on the semantic of your class you could use either.
因此,根据您的类的语义,您可以使用两者之一。
Most of the times (+90%)  I do the first: void add( A other ){}
大多数时候(+ 90%)我做第一个: void add( A other ){}

