Search code examples
javaprimitive

How to overcome the fact that primitives are passed by value


I have a long piece of code that calculates two values (doubles) for me, I use this piece of code in a few places - to stick with DRY principles I should refactor this bit of code to a nice unit testable method. However I cant make it return two doubles, and doubles are primitive so cannot be passed by value and manipulated. The cleanest way I can think of doing this is by making this method return an double[]. Can anyone think of a better way?

Thanks


Solution

  • Firstly, all variables are passed by value in Java, not just primitives. It's just that objects can be mutable. It's important to understand that. For example:

    public void addHour(Date date) {
      date.setTime(date.getTime() + 3600 * 1000);
    }
    

    The date is passed by value but Date is mutable so it can be modified but try and do this:

    public void addHour(Date date) {
      date = new Date(date.getTime() + 3600 * 1000);
    }
    

    and it won't change the date. Why? Because date is a reference but is passed by value.

    Secondly, do these doubles relate to each other in some way? If so wrap them in a class than describes this relationship like:

    public class Coordinate {
      private final double x;
      private final double y;
    
      public Coordinate(double x, double y) {
        this.x = x;
        this.y = y;
      }
    
      public double getX() { return x; }
      public double getY() { return y; }
    }