Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Variables : Good or Bad? [duplicate]

Tags:

java

static

Possible Duplicate:
Why are static variables considered evil?

I have the habit of using static variables extensively in all my programs, especially when I am working with Android. I tend to use them because sometimes it feels so cumbersome to send 10 or more values via Intents. So, I just declare them as static variables and access them in the other classes easily by using the "dot" operator. Another reason for using static variables is when I am making a Utility class to be used throughout my application. Like the code I have given below helps me to use the variables in different activities.

Utility.java

public class Utility {
public static Facebook fb;
public static AsyncFacebookRunner fbAsyncRunner;
public static String[] fbPermissions = {"email", "read_stream", "user_birthday"};
public static final String PREF_UTILITY_FILE_NAME = "PrefUtilityFile";
public static SharedPreferences prefs;
public static Editor editor;
public static String access_token;
public static long expires;
}

I searched online for similar questions and came across this and this, but they do not seem to give a final answer to the issue. And in most of the places, I see conflicting opinions and hence am totally confused.

Is it a good programming practice or bad ? Should I be using it or not ?

like image 626
Swayam Avatar asked Sep 19 '12 10:09

Swayam


People also ask

Why static variables are bad?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Is static method good or bad?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Are static variables good practice?

Static Methods/Variables are bad practice. In short: Yes. There are many disadvantages and static methods should almost never be used. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world.

Are static variables bad for performance?

Defining a variable static in a method only means that the variable is not "released", i.e. it will keep its value on subsequent calls. It could lead to performance improvement depending on the algorithm, but is certainly not not a performance improvement by itself.


2 Answers

You can replace all you static fields with a "Context" object which you can pass around or make a Singleton. It is possible to remove almost all your static fields away. Whether this is a good idea or not is up to you, but I wouldn't assume that it has to be much harder to use instance fields.

BTW: I would suggest

  • placing static fields/constant with the class or package which uses them
  • treat static arrays as immutable if possible making them final as well.

You can use a non-static Context with

public class Context {
    public static final String PREF_UTILITY_FILE_NAME = "PrefUtilityFile";

    public Facebook fb;
    public AsyncFacebookRunner fbAsyncRunner;
    public String[] fbPermissions = {"email", "read_stream", "user_birthday"};
    public SharedPreferences prefs;
    public Editor editor;
    public String access_token;
    public long expires;
}

// pass to constructor as required
class UsesContext {
    final Context context;
    public UsesContext(Context context) {
        this.context = context;
    }

    public void method() {
        // can use context
    }
}

This allows you to create unit tests with multiple Contexts.

The only thing I would leave static are constants.

like image 95
Peter Lawrey Avatar answered Oct 21 '22 02:10

Peter Lawrey


This programming practice is bad in purely object oriented languages (like Java) because it undermines the object oriented programming paradigm. They work, but once you realize you DO need more than one version of them, you will need a lot of refactoring to achieve that.

If you think that handing too many parameters via method calls is cumbersome. Simply create an object that holds all of them (see Peter Lawrey's answer, "Context" object) and pass only this object. Then you can again use your "simple dot notation" on that object.

Next point: Testing. If you need to replace some static fields with proxy or other testing stuff for unit tests, you are basically screwed. With a context object, you can simply hand a different context object into the unit tests.

The Utility class you mentioned is basically a good candidate for such context object. Simply make all its fields non-static and hand in an object of that class to code that needs it.

I can tell you about one example where I got screwed by using statics: I once wrote a compiler. And since I thought that during a compilation run, there are many context things that are only necessary once (the symbol table, for example), I added them all as static variables. Later I decided to allow multi-threaded compilation and a "server" mode where the compiler runs all the time in idle mode until a client sends a compile request (this saves Java's long startup time). Now I was screwed. Now there was more than one concurrent context (concurrent compiler threads), but all context was shared via static variables. I needed around one week to replace all statics by context objects and introduced numerous bugs.

like image 32
gexicide Avatar answered Oct 21 '22 02:10

gexicide