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) { /* ... */ }
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?
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?In Java, as far as I can tell, Collections generally modify themselves (and so does Collections.add).
However, non-Collections object (e.g. Vector2D) varies more. Among the conventions I’ve seen:
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.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.)