Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for defining a Java variable that acts (something) like a C's local static variable

Tags:

java

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.

like image 703
JohnnyLambada Avatar asked Apr 17 '12 20:04

JohnnyLambada


3 Answers

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);
   }
}
like image 120
Jonathon Faust Avatar answered Oct 16 '22 23:10

Jonathon Faust


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.

like image 44
Colin D Avatar answered Oct 17 '22 00:10

Colin D


In C a function static variable

  • has the life of the program
  • has the scope of the function

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() ....
}
like image 27
Miserable Variable Avatar answered Oct 16 '22 22:10

Miserable Variable