2015年8月1日 星期六

java local variable vs class variable


source : http://stackoverflow.com/questions/5539652/using-a-class-variable-vs-sending-local-variable-to-functions-methods

local variable to a function/method as a parameter, rather than using a class variable in place of the function/method variable.

The only answer out of the blue, for a any generic case is: it depends on your specific case. Data members, static members and function arguments all serve different purposes. Of course, there are some key tips we can give for what types of signs you should look for choosing one or the other.

Typical cases:

Data member: the value is part of the object's (as in instance of a class) state. You want other calls to methods to reflect this particular state.
Static member: the value has simultaneous, identical meaning to all instances of the class. This is typically used only for constants (even when initialized at runtime, like a singleton) but in some cases, there is need for mutable class state.
Function argument: the value has meaning only for a specific execution of the function/method. This value is subject to change from one invocation to the next.
There are some common symptoms of bad choice.

Consider the following questions:

Do you always pass the same value to a method, no matter where you call it from? Consider making the argument a constant and hiding the argument away. Consider defining overloads: one without argument for the common case and one with argument for flexibility.
Do you need to set a data member (via a setter) every single time you invoke the function? Consider making the value an argument to the function. There's no need to save on the function signature if you need to replace each call with two lines to set the value before hand.
I'm under the impression that you and your co-worker are in a simple misunderstanding of the nature of this parameter. Make sure you clearly understand your co-worker's arguments and make yourself clear. Try to rephrase what it is that you're trying to say.

沒有留言:

張貼留言