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
someStructwith the behavior ofmyFunccleanly, but it’s extra overhead for understanding and maintaining things. Might be worthwhile, might not be.