I have got a question regarding program style. Within a class, is it better to pass a variable to a method or to access the field inside a method?
public class NumberTest{
private int num;
public NumberTest (int num){
this.num = num;
calculateX(num);
calculateY();
}
private void calculateX(int num){
System.out.println (num);
}
private void calculateY(){
System.out.println(num)
}
}
I'll differ from the others here...
Where it is at all reasonable, I like to pass in the argument. This very slightly decouples the method from the class implementation, and makes it easier to unit test. For example, sometimes it is a pretty complex process to set this.num to 94404 due to other constraints.
e.g. this is a Zip Code but your business logic requires that it must match the State and Country field. Or, in practice this field is read from a Database, a Web Site, etc...
If you pass the argument, your unit test can shortcut and just pass in the value. And, in the off chance you might have a future special case where you don't want to use what's in the class field, you can do it.
Now, if you are using 27 class fields, you obviously don't want to pass in 27 arguments. But, IMO, if it's 1 or 2, I like to pass them in.
Minor Noted added after acceptance:
There is another possible difference between passing in the arg and using a field. In a multi-threaded environment, using a passed in argument may be safer that reading from a field. The field might get changed in the middle of the function, while a passed in argument, depending on type and usage, is less likely to change. In this example, a passed in int num will never change unexpectedly, but this.num might.
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