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;
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With