Java add()方法约定 [英] Java add() method convention

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

问题描述

所以,我通常是一个红宝石程序员,因此我对Java约定的掌握至多是不稳定的。如果我有一个A类并且想要定义一个方法来添加该类的两个实例,那么行为和返回类型的约定是什么?

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?

public class A
{
    //...
    public NotSureWhatTypeItShouldReturn add (A that) { /* ... */ }

我应该


  • 返回一个表示成功的布尔值修改目标,或

  • 返回目标的修改副本并在出错时抛出异常

哪种方法适合这种方法的普通Java约定?

Which fits with the normal Java convention for this kind of method?

推荐答案

这里的每个人都在考虑Collections.add()型方法;但我怀疑这是你在想什么。你是否更喜欢 Vector2D.add(),它将Vector2D的x和y组件加在一起?

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?

在Java中,据我所知,集合通常会自行修改(Collections.add也是如此)。

In Java, as far as I can tell, Collections generally modify themselves (and so does Collections.add).

但是,非收集对象(例如Vector2D)的变化更大。在我见过的约定中:

However, non-Collections object (e.g. Vector2D) varies more. Among the conventions I've seen:


  1. Cls add(Cls b)返回一个新对象,不修改现有实例

  2. void add(Cls b)修改 this 并且不返回任何内容(即返回void),它不应该修改 b 。返回 bool 是没有意义的,因为这种类型的添加永远不应该失败(如果它确实存在,则异常是合适的。)

  3. Cls add(Cls a,Cls b)返回一个新对象,既不修改也不修改b。 Cls.add()是Cls类中的静态方法。

  1. Cls add(Cls b) which returns a new object and does not modify existing instances
  2. void add(Cls b) which modifies this and returns nothing (i.e. returns void), it should not modify b. There is no point in returning bool since this type of addition is never supposed to fail (and if it does anyway, an Exception would be appropriate).
  3. 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.

就个人而言,我更喜欢算术风格的第一个样式add() ;正是因为我们可以做a.add(b).add(c).add(d)看起来有点像a + b + c + d。 (如果 a 是一个集合,我通常不这样做;因为对于集合对象,序列添加看起来很奇怪。)

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 a is a Collection; since serial addition looks weird for Collections object.)

这篇关于Java add()方法约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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