HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Static variable Current in Application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
currentvariablestaticapplication

Problem

I was finding myself frequently calling getApplication() and casting it as MyApplication so that I could call a method in MyApplication. I decided to declare the static variable Current in MyApplication and set it in the constructor. Now I don't have to do the casting.

Are there any pitfalls to taking this approach?

public class MyApplication extends Application {
    public static MyApplication Current;
    public MyApplication(){
        super();
        Current = this;
    }
    public void doSomething(){

    }
}

public class MyActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.Current.doSomething();
    }
}


Below is, I think, the normal approach for getting the application and calling the method.

public class MyApplication extends Application {
    public void doSomething(){

    }
}

public class MyActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MyApplication)getApplication()).doSomething();
    }
}

Solution

With this solution there is a danger that somebody accidentally change MyApplication.current to null or an invalid reference.

I'd override the getApplication method in the MyActivity class with a covariant return type:

@Override
public MyApplication getApplication() {
    return (MyApplication) super.getApplication();
}


According to the Code Conventions for the Java Programming Language, Current should be current.

Code Snippets

@Override
public MyApplication getApplication() {
    return (MyApplication) super.getApplication();
}

Context

StackExchange Code Review Q#8353, answer score: 3

Revisions (0)

No revisions yet.