Reputation: 1638
When I have static method what is a good place to declare scope variables? Inside method body or outside?
public static void myMethod()
{
int myVariables;
//body
}
private static int myVariables;
public static void myMethod()
{
//body
}
Upvotes: 2
Views: 724
Reputation: 13676
I'd say that :
1. As parameter to a static method
// this is the best because you can easily test your method by passing mock values and it'll be removed by GC as soon as method ends
2. Local variable
// this is kind of 'ok' but the problem are there when you try to unit-test your method. It'd be very difficult to check what your local method variable is assigned to (does it has correct value or not). It'll be removed by GC as soon as method ends.
3. Static field in class
// While this should be generally avoided it is a good idea in case where you're going to re-use it in different methods of your class or even outside of it. It'll be removed by GC when a reference to your class is lost.
Upvotes: 1
Reputation: 1185
it's Depend your task.You should declare variables at the smallest scope possible.
if you are want to access globally you should define as bellow
private static int myVariables;
public static void myMethod()
{
//body
}
you want to access only inside the method you should define as bellow
public static void myMethod()
{
int myVariables;
//body
}
Upvotes: 1
Reputation: 325
If you use the variable only in the method scope, declare them inside the method, because the memory that is allocated by it can be freed after the method returned.
If you need to store some variable across multiple method calls, define them outside the body, so they will not freed after a method call.
Upvotes: 1
Reputation: 77294
You should declare variables at the smallest scope possible. So if a local variable works, stick with the local variable (Option 1).
Only if you cannot do what you want to do with a local variable, consider a field or property.
Upvotes: 7