3
\$\begingroup\$

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();
    }
}
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Couldn't he also just put that getApplication() method on MyApplication, like MyApplication.getCurrent()? Point, as you say, is to provide read only access to the instance. \$\endgroup\$ – Lars-Erik Jan 27 '12 at 12:10
  • \$\begingroup\$ I'm not too familiar with Android and I could imagine some situation when super.getApplication() returns a proxy or wrapper class instead of the direct reference to the MyApplication instance. I don't know it is possible or not. On the other hand, static fields usually makes testing harder, so I try to avoid them. \$\endgroup\$ – palacsint Jan 27 '12 at 12:29
  • \$\begingroup\$ Well, in this case MyApplication is obviously intended to be a single instance, so changing the "Current" member to private and exposing a static getter shouldn't be an issue imho. But I don't know Android either, so add a pinch of salt. (aren't more or less all mobile apps single instanced?) \$\endgroup\$ – Lars-Erik Jan 27 '12 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.