When is it good form to push a local variable to a function/method as a parameter, rather than using a class variable in place of the function/method variable.
For instance, I can have a function:
int DoSomething(int var)
{
if(var == -1)
return 0;
}
or I can have a class variable "_var" and use it in the same function, like this:
int DoSomething()
{
if(_var == -1)
return 0;
}
I'm of the mind to, if we have a class variable to be used in some function/method, called DoSomething
in my example above, that I should send the DoSomething
function/method the class variable as a parameter, so that the function is easier to read and test.
When is it good form to do either? I know this is a loaded question, but I'm trying to make a case for my argument with a co-worker, and they're stating that I would add more code to the function/method signatures, rather than keeping the function/method signatures smaller.
In my mind, I'm making the code cleaner and easier to maintain by pushing the class variable(s) to the respective functions/methods, rather than forcing them to rely on/know about a class variable's existence.
Please advise.
Class variables are declared when a class is being constructed. They are not defined inside any methods of a class. Because a class variable is shared by instances of a class, the Python class owns the variable. As a result, all instances of the class will be able to access that variable.
The main difference between instance variable and local variable is that instance variable is a variable that is declared in a class but outside a method, while a local variable is a variable declared within a method or a constructor.
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:
There are some common symptoms of bad choice.
Consider the following questions:
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.
I look at it in terms of dependency, i.e. who is dependent on the variable (in your case var
), is it a method or a class?
For e.g. JavaBeans have class variables that are dependent by the class, so if the class needs these variables then DoSomething()
is best.
Alternatively, if you class doesn't care about var
and doesn't need it anywhere else, and only DoSomething()
requires var
, then DoSomething(int var)
is essential.
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