Question about Java parameter

I have a general Java question that I am looking for an answer to. Suppose I have an object with a property height, and I have a method that uses height to calculate. Is it better to pass the height of the property to the method or not to pass the complete object and use the getter to get the height value. Hope this makes sense.

eg.

public getHeightInMeters(Object object) {
    return object.getHeight()*x;
}

- is it the same, worse, better than?

public getHeightInMeters(Height height) {
    return height*x;
}
+5
source share
8 answers

It depends.

If the operation you are performing is semantically related to the type of an object, it makes sense to pass in the object. Or if you use several properties of the object.

If the operation is general, that is, it is applied to the whole, not to a specific property of the object, and then just takes an integer.

+2

. . getHeightInMeters() , .

+2

. getHeightInMeters ? , .

, - Height, .

+2

- / .

, . , , / , .

, , , .

+1

, , . , , , .

, , .

0
class Person {

private double height;

public void setHeight(double height){
   this.height = height;
}

public double getHeight(){ 
  return height;
}
}

, .

public class Converter{

public static double convertFromMeterToInch(double meters){
 return meters * 'some factor you get from net'
}

public static double convertFromInchtoMeter(double inch){
 return ....
}
}
0

:

, , . , , , , .

, get , , . . , , pixelsToMetters(int pixel), .

0

getXXXX() , , - :

public double getHeightInMeters() {
    return this.height*x;
}

If you need a simple converter, name it differently and pass in double, as it does nothing with the object you are passing. Thus, you can reuse this method for any other context.

Keep things simple!

0
source

All Articles