Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parameter passing question

Tags:

java

I have kind of a general java question I'm looking for an answer to. Lets say I have an object with a property height and I have a method that uses height to make some calculation. Is it better to pass the property height to the method or is it any different to pass the full object and use a getter to retrieve the value of height. I hope this makes sense.

e.g.

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

is the same, worse, better than?

public getHeightInMeters(Height height) {
    return height*x;
}
like image 591
thurmc Avatar asked Jun 14 '11 16:06

thurmc


4 Answers

It depends.

If the operation that you are performing is semantically linked to the type of object then it makes sense to pass the object. Or if you are using more than one properties of the object.

If the operation is generic, that is, it applies to an integer rather than to a specific property of the object then just accept an integer.

like image 192
Vincent Ramdhanie Avatar answered Oct 21 '22 23:10

Vincent Ramdhanie


The second version is better. I has a less complicated signature. Since the getHeightInMeters() method only needs the height value, you should keep it simple.

like image 20
Joe Zitzelberger Avatar answered Oct 21 '22 22:10

Joe Zitzelberger


The second. Does getHeightInMeters care anything about object? If not, then it doesn't need it.

All it needs is Height, so that's what you should pass it.

like image 2
Reverend Gonzo Avatar answered Oct 21 '22 21:10

Reverend Gonzo


The second one is the best/proper way.

It's better to pass in the property height, because you break down the dependency. That is, if you change the passed in object, delete/rename method, you will end up with huge head-aches.

Furthermore, if you just pass in the property height, you will always know what goes in and what comes out.

like image 1
Shef Avatar answered Oct 21 '22 23:10

Shef