26

So my coder friend hates using the static coding. Yet my Java program is full of it to link between classes, and I have a lot of them!

Is it worth rewriting the whole code to remove the static method?

Is there any advantage of using one over the other?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Kezz
  • 1,680
  • 3
  • 19
  • 37
  • 3
    I find that using static variables to keep state makes your programs unmaintainable, it's basically like using global variables. Private statics within a class do not have the same problem since there isn't code accessing it from everywhere, i.e, spaghetti code. – Ruan Mendes Aug 10 '12 at 18:25

9 Answers9

41

1. An instance variable is one per Object, every object has its own copy of instance variable.

Eg:

public class Test{

   int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will have its own copy of x.

2. A static variable is one per Class, every object of that class shares the same Static variable.

Eg:

public class Test{

   public static int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will have the exactly one x to share between them.

3. A static variable is initialized when the JVM loads the class.

4. A static method cannot access Non-static variable or method.

5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.

kylegill
  • 314
  • 1
  • 12
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • 6
    I don't think the question is what are static variables and why they're bad. It's whether it's worth it to remove the static variables that his coder friend says are bad. – Ruan Mendes Aug 10 '12 at 18:57
  • 5
    I have described what they are and how they are associated with the Class. Now its upto the coder friend to decide whether to use or not... I have also mentioned in my 5th point that how it gets bad sometimes – Kumar Vivek Mitra Aug 11 '12 at 09:14
7

static is for the cases where you don't want to have copy for each instance

instance variables are for the cases where you want separate copy for each instance of object.

Based on business cases, which one to use may change.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • The problem is that static fields are usually an instance of code-smell. Specially as the OP mentioned, since they're used for communication between classes, they're basically global variables. I stay away from any public static variables that aren't readonly. – Ruan Mendes Aug 10 '12 at 18:23
  • @JuanMendes: agree with your comment. – kosa Aug 10 '12 at 18:29
  • Is this the same as using it for functions as well as variable? – Kezz Aug 10 '12 at 19:39
  • @user1590990: This principle is same for both methods and variables. – kosa Aug 10 '12 at 19:45
  • @thinksteep So basically all the static methods I use are just different functions (that could be all in one class) but I have separated them due to easyness... Would this be acceptable use of Static? – Kezz Aug 11 '12 at 14:39
  • 1
    @Kezz101 Static functions that don't access any static variables (completely stateless) are fine. From what you're saying, you're using static functions to hold application state, that's what you shouldn't do. If you post some of your static functions (small ones) we should be able to comment more accurately about your situation. – Ruan Mendes Aug 11 '12 at 18:22
  • @JuanMendes Well the GitHub for my project is [here](https://github.com/kezz101/HarryPotterSpells): it does now hold the fully instanced version. The original, with statics, is [here](https://github.com/kezz101/HarryPotterSpells/tree/24ca96144225a1fee908b91f422ecfab955923e5) – Kezz Aug 11 '12 at 18:34
  • @JuanMendes all of them contained Static functions/variables. They now contain instances – Kezz Aug 11 '12 at 19:37
5

If you have too many static functions and variables it can lead to a more functional approach rather than true OO. Also if you have public static variable then you replicate global variable which are not good. Keeping track of them is a nightmare.

Generally my rule is to use instance variables if you can and only have static variables and functions if it really is generic over a class rather than an object

This is quite a good answer to a similar questions Java: when to use static methods

Rather than just linking to methods consider using the new operation to create a new object and access the method from that in a non static way.

before

public void myMethod(){
    Time.setTime(Time.getTime() + 20);
    System.out.println(Time.getTime());
}

after

public void myMethod(){
    Time t = new Time();
    t.setTime(t.getTime() + 20);
    System.out.println(t.getTime());
}

Any state that is held in these methods will now be the to instance of time you have created. You could also share the variable t accross other methods if you needed to.

Community
  • 1
  • 1
RNJ
  • 15,272
  • 18
  • 86
  • 131
  • So what exactly is so bad about public static variables? – Kezz Aug 11 '12 at 14:14
  • The trouble is that they immitate global variables. These can be updated anywhere in the code which make it very difficult to follow where there are updated and what state they are in. It can lead to bugs which are very hard to find. This link is quite good at explaining it. http://c2.com/cgi/wiki?GlobalVariablesAreBad If you want more clarity let me know – RNJ Aug 12 '12 at 21:26
3

Garbage Collection - static fields live much longer then instance fields. From a logic point of view, static fields are ONLy suppose to be shared among every single instance - if it is truly your case then no problem of course.

Eugene
  • 117,005
  • 15
  • 201
  • 306
1

Are you talking about static methods or static properties?

As far as static methods are concerned, there is only one way to abuse them, and that is when you define methods that take an object instance as a parameter. You should never need to do that and in my view doing so is poor coding practice. Here is an example:

static int add(ThisClass a, ThisClass b) {
   return a.value + b.value;
}

If you are talking about static variables in the class, you are basically into the subject of "singletons" which is where there is intended to be only one instance of a particular class. Singletons are subject to a lot of abuse. They are used by many class libraries (think JDNI and the logging classes) but if an application makes extensive use of them it can be a sign of a poorly structured program. That is probably what your friend is bitching about.

AlanObject
  • 9,613
  • 19
  • 86
  • 142
1

Instance and Static variable:

Answer to your Question: I would say it is worth to use static variable to save memory allocation.

Memory allocation:

For static variable only one memory location is allocated irespective to no of object created and for Instance variable each object one memory location allocated

Now consider this example, consider you are working on companies internal project where you have to create 1M object to Employee class and some property to the Employee class are eid, ename, ecompany now Important thing is that all employees are working in XYZ company so value to the property ecompany is gonna be "XYZ" irrespective of Employee.

Now you know the situation, value to the property ecompany is gonna be XYZ for 1 Million Object.

Now you decide you want to declare ecomapny property as static or instance considering memory allocation

if you declare it as a static then minimum memory allocated to ecompany will be only 48 bytes which very less compare to memory needed to store 1 Million instance variable. 100000 * 48 bytes = 48 Million bytes.

0

When you use static objects (except for the case of singleton) you're actually implementing functional programming combined with global variables. If you do that a lot - you should reconsider either your design or using Java (maybe you should use a functional programing language such as list, scheme etc).

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

Pro Static

Once a static member is called from the inside or the outside of the class, then the static constructor of the class is called. The "static object" will live through the whole session, hence you will win in performance.

Con Static

Static members cannot have states, hence they cannot talk to non-static members of the class.

Example

If we consider the BigInteger class, this class would gain if some of the parts were made into static members.

An instance of the class represent (as expected) a big integer.

However, the main methods add and multiply are not static (which they should be in a better world), which is bad for performance.

Hence, in practice one should not be afraid of mixes between static and non-static.

0

I don't like using static variables or methods because they have no real inheritance. This makes it more difficult to mock for testing. Using instances gives you the flexibility of full polymorphism. On the other hand, sometimes static variables are necessary, for example with a global cache. Static methods can be a benefit if they provide helper methods for classes/objects/primitives which you cannot access or extend. These helper methods are so simple they don't need inheritance. For example java.util.Arrays class or java.util.Collections.

Maarten
  • 808
  • 1
  • 6
  • 17