I’m porting some Objective C code to Java. One of the C methods looks like this:
void method(){
static int variable;
...
}
My understanding of this is that variable has a lifetime equal to the execution life of the containing compilation unit but visible only to the method. AFAIK, there is no equivalent for this in Java so I am considering using class level static variables to do the job. I understand the risk of widening the visibility of the variables and the resultant decrease in maintainability but if I carefully check all of the other methods of the class for clashes, I can handle that with judicious commenting.
Am I missing anything? Any other risks I should consider?
Thanks to all for your contributions to SO.
Cheers
Simon
You should really consider what state is logically part of. Is it actually part of the state of an instance of the containing class? If so, make it an instance variable. Is it logically state of the type itself? If so, a static variable is reasonable – but statics are often the enemy of testability, threading etc.
Is it actually logically part of state of a different class? Possibly a new one which doesn’t exist yet? You might want to have a static final reference to an instance of that new class, for example.
Basically, let the natural location of the state inform the location of the variable.