In C, I can create a static variable in a function. The space for that variable is not allocated along with the function variables, it's allocated at program startup time. (Don't mock my C too harshly, I've been programming in Java for way too long :)
void myFunc(){
static SomeStruct someStruct;
someStruct.state=INITIALIZED;
goDoSomethingInteresting(MY_COMMAND,&someStruct);
}
In Java, if I want to do something similar, I create a class variable and then use it.
Class TheClass {
SomeStruct someStruct = new SomeStruct();
void myFunc(){
someStruct.setState(INITIALIZED);
goDoSomethingInteresting(MY_COMMAND,someStruct);
}
}
My question is what is the best practice for doing something like this? I'd really like to associate my variable someStruct
with my function myFunc
, because myFunc
is the only code that should know about or use someStruct
, but there's no way to make that association except to put the variable close to the function in code. If you put it above, then the Javadoc for the function looks wonky, if you put it below, then it's not very clear that they belong together.
Normally I would just create someStruct
locally, but in my case it's very expensive to create someStruct
, and I call myFunc
in a tight loop.
A small class will associate someStruct
with the behavior of myFunc
cleanly, but it's extra overhead for understanding and maintaining things. Might be worthwhile, might not be.
class TheClass {
MyFuncBehavior myFuncer = new MyFuncBehavior();
void myFunc() {
myFuncer.myFunc();
}
}
class MyFuncBehavior {
private static SomeStruct someStruct = new SomeStruct();
public void myFunc() {
someStruct.setState(INITIALIZED);
goDoSomethingInteresting(MY_COMMAND,someStruct);
}
}
Since you are writing the java class, just make it a private member of your class. Put a comment next to it if you want to stop other people who might be working on that same file from using it elsewhere in the file.
In C a function static variable
That is, once initialized it has available on every call to the function with the last value assigned to it but is not accessible outside the function.
This will fit nicely if you convert the function into a class with one method and make the static variable a member of that class.
e.g.
void F()
{
static int i;
}
Becomes
class F
{
int i;
func() ....
}
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