Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overcome the fact that primitives are passed by value

Tags:

java

primitive

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

like image 949
Aly Avatar asked Nov 27 '22 05:11

Aly


2 Answers

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; }
}
like image 98
cletus Avatar answered Dec 05 '22 16:12

cletus


You could encapsulate them in a class for this purpose.

You could also give a double[] parameter to the method that calculates them and where it will put the calculated values in. This can be rather efficent as the caller code can reuse this array for successive invocations if performance is important.

like image 28
x4u Avatar answered Dec 05 '22 17:12

x4u