Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

static variables in functions?

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
I was trying to declare a static variable inside a function, and Eclipse told me I can't do that. :-(
Ex.
Code:
class Blah
{
   public void Func()
   {
      static int counter = 0;
      ++counter;
      System.out.println( "This function was called " + counter + " times." );
   }
}
This use of static is perfectly legal in C++, so I can't figure out why Java doesn't like it? I know I could move the static variable to the class level, but since it's only used in that one function, that would just clutter up the class namespace and isn't good encapsulation.

Is there any other way to do what I'm trying to do?
 
No.
I can't tell you why it isn't legal in Java, but it is.
I can't imagine another way, which wouldn't clutter up the namespace at a different place and wouldn't be a more poor encapsulation like:
Code:
class BlahFuncCounter 
{
      private static int counter = 0;
      public static void increment ()    
      {
            ++counter;  
            System.out.println( "This function was called " + counter + " times." );
      }
}

class Blah
{
   public void Func()
   {
      BlahFuncCounter.increment ();
   }
}
This would just shift the problem to another place, and using an inner class wouldn't be of advantage too.

seeking a job as java-programmer in Berlin:
 
I would go for :

Code:
class Blah
{
   static int counter = 0;

   public void Func()
   {      
      ++counter;
      System.out.println( "This function was called " + counter + " times." );
   }
}

I have to say I never liked the way in C/C++ you can declare a static var inside a function like that - it looks messy to me, as it looks as if 'counter' is set to '0' each time - but of course its only set to '0' once.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
But surely any variable decalred within a method block is scoped to that method. And since statics in Java are scoped to the class, defining them in a method would be nonsense (to my mind anyway).

Expecting something to work in Java simply because it works in C++ is heading for trouble.

I would say that since the methods in a class service the responsibility and behaviour of that class, then it isn't really breaking encapsulation much by having the static declaration at class level. If this makes your class hard to understand and maintain, then maybe your classes are too big and their responsibilities too wide ranging.

However, I'm not 'God's Gift' to OO design so I'm open to discussion on this.

Tim
 
I don't think it's too confusing once you've used it a few times...
What if the function is also static? Would it be legal to have static variables inside a static function? (which wouldn't help in my case since I'm not using a static function)
 
It's confusing: what happens if the method is never called? Does the variable exists or not? Static variables refers to classes. A static variable in one class just accessed in one method can be declared in the class without problems.

Cheers,
Dian
 
Diancecht said:
what happens if the method is never called?
If the method is never called (and if local static variables were allowed) then it doesn't matter if the variable exists or not since only that method uses it.
 
So you set a breakpoint to debug that class outside that method and cannot know the value of the variable. Not logic for me: if you want a variable to be static and unique for a type of object, give it the scope of the object.

Cheers,
Dian
 
But if it's a local (function level) variable, why would you need to know the value of the variable unless it's actually being used?
 
Because if you define the scope of a variable, you don't just define where it can be accessed but its lifetime. A method scope variable vanishes when the method ends. If you don't want it to end, then it's time for a global variable.

Cheers,
Dian
 
I'm pretty sure I'll just have to use a static class member variable, but it's still bad encapsulation since then every member function will have access to it.

For example, if you're the only developer that's working on that class and that will ever work on that class, then you shouldn't have much of a problem remembering that only 1 function is allowed to touch that member variable; but if you have multiple developers getting their hands into the code, they might not understand that fact and use the variable in other functions... Comments would help, but I've seen plenty of code that is virtually commentless. If the compiler could enforce those types of security constraints for you, why not let it?
 
If there's a static variable inside a class that only a method can access maybe you're not doing a good OO design.

And the compiler cannot stop that: if the developer wants to access that variable, he just need to declare it global and static. If you don't document your code and people without specific knowledge is modifying it, there's nothing the compiler can do about.

Cheers,
Dian
 
if the developer wants to access that variable, he just need to declare it global and static
Yes, that's the problem I've run into with Java since I can only declare the static variable to be global to the class. But what I'm saying is, if Java would allow static variables in functions the way C/C++ does, then unless a developer specifically moves the variable declaration from the function level to the class level, nobody outside that function can access it.

Try taking the word "static" out of the picture for a second and think of a normal variable. Would you rather do:
Code:
class AllGlobals
{
   private int counter;
   private String msg;
   private boolean ret;

   public boolean func1( int x )
   {
      ret = true;

      for ( counter = 0; counter < x; ++counter )
      {
         // Do something...
      }

      if ( /* some condition */ )
      {
         msg = "condition failed in func1()!";
         System.out.println( msg );
         ret = false;
      }

      return ret;
   }

   public boolean func2( int x )
   {
      ret = true;

      for ( counter = x; counter >= 0; --counter )
      {
         // Do something...
      }

      if ( /* some other condition */ )
      {
         msg = "condition failed in func2()!";
         System.out.println( msg );
         ret = false;
      }

      return ret;
   }

   // ...
}

or this:

Code:
class AllLocals
{
   public boolean func1( int x )
   {
      boolean ret = true;

      for ( int counter = 0; counter < x; ++counter )
      {
         // Do something...
      }

      if ( /* some condition */ )
      {
         String msg = "condition failed in func1()!";
         System.out.println( msg );
         ret = false;
      }

      return ret;
   }

   public boolean func2( int x )
   {
      boolean ret = true;

      for ( int counter = x; counter >= 0; --counter )
      {
         // Do something...
      }

      if ( /* some other condition */ )
      {
         String msg = "condition failed in func2()!";
         System.out.println( msg );
         ret = false;
      }

      return ret;
   }

   // ...
}
Also imagine that these classes are running in a multi-threaded app.
 
In your last example, I don't see any reason, to share the variables msg, counter and ret.

If you need more than one static variable, declare a second. I seldomly need many static variables of the same name.

seeking a job as java-programmer in Berlin:
 
I don't see any reason to share them either, which is why I would use the second example instead. I was just trying to put my point across with an example that doesn't use static variables.

I've been working with computer security software for over 8 years, so I write my code as securely as I can. When I declare any variable, function or class, I always give it the absolute minimum visibility that it requires. i.e. all data is available on a need to know basis. So if only 1 function needs to have access to a variable, then I declare that variable inside the function to protect it. I don't do that to make the code any more secure against hackers; I do it to protect the code from itself (or rather from the developers who write the code).
 
Look, Java is Java and C++ is C++. They each have advantages and nice bits, and some disadvantages and nasty bits. Let's not descend into a 'C++ does it so why can't Java'. Different languages. Period.

The unit of Encapsulation in Java is the class. You'll have to accept this, or don't use Java.

Tim
 
Well, there's always a compromise between secutiry and readibility. If you want to keep your software secure, you have millions ways, you can just encrypt it and variables will mean nothing.

If you want to define a variable inside the scope of a method, then you're using local variables, no need for static. If you're using that variable each time you enter the method and want to keep the value, then it's over the scope of that method, and above the method you have the class.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top