Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable data in Java - static or instance operators?

Imagine any Java class which is entirely immutable. I will use the following as an example:

public class Point2D {
  public final int x;
  public final int y;

  public Point2D(final int x, final int y) {
    this.x = x;
    this.y = y;
  }
}

Now consider adding an operator on this class: a method which takes one or more instances of Point2D, and returns a new Point2D.

There are two possibilities for this - a static method, or an instance method:

public static Point2D add(final Point2D first, final Point2D second) {
  return new Point2D(first.x + second.x, first.y + second.y);
}

or

public Point2D add(final Point2D other) {
  return new Point2D(this.x + other.x, this.y + other.y);
}

Is there any reason to pick one over the other? Is there any difference at all between the two? As far as I can tell their behaviour is identical, so any differences must be either in their efficiency, or how easy they are to work with as a programmer.

like image 546
Christopher Riches Avatar asked Mar 05 '23 22:03

Christopher Riches


1 Answers

Using a static method prevents two things:

  • mocking the class with most mocking frameworks
  • overwriting the method in a subclass

Depending on context, these things can be okay, but they can also create serious grief in the long run.

Thus, me personally, I only use static when there are really good reasons to do so.

Nonetheless, given the specific Point2D class from the question, I would tend to actually use the static methods. This class smells like it should have "value" semantics, so that two points for the same coordinates are equal and have the same hash code. I also don't see how you would meaningfully extend this class.

Imagine for example a Matrix2D class. There it might make a lot of sense to consider subclasses, such as SparseMatrix for example. And then, most likely, you would want to override computation intensive methods!

like image 52
GhostCat Avatar answered Mar 09 '23 21:03

GhostCat