Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for Organizing Android Code

I have been coding an Android app that has a lot of code dedicated to it. As you can imagine, there's lots of case-driven code in there. Because most of Android callback functionality is based on integers and ItemIDs and requestCodes, there is a lot of functionality built into switch statements or if-then-else constructs.

What are the best practices for organizing/refactoring this code in a better way? What have you found that works to reduce the amount of code and clarifies it at the same time? Is a huge amount of small classes going to hurt Android performance?

Thanks in advance.

like image 988
frethop Avatar asked May 31 '26 08:05

frethop


1 Answers

A large number of classes is not going to affect the performance of the application. Some good practices in Android, however, include placing values like integers, item IDs, and request codes into a Resources xml file.

You will also see a lot of Callback classes as inner interfaces of the Object they relate to:

public class MyObject
{

    private Callback callback;
    private Object returnObject;

    public void setCallback(Callback callback) 
    {
        this.callback = callback;

    }

    public void doSomething()
    {
        //do something - could be an anync task or other that assigns returnObject
        callback.invoke(returnObject);
    }

    public interface Callback
    {
        public void invoke(Object obj);
    }
}

Then you can use this as follows:

MyObject obj = new MyObject();
obj.setCallback(new MyObject.Callback() {
    @Override
    public void invoke(Object obj) {
        Log.i("Callback", obj.toString());
    }
});
obj.doSomething();
like image 119
Phil Avatar answered Jun 01 '26 20:06

Phil