mercredi 27 juillet 2016

Design Pattern: Using Null to minimize heavy Database Queries

I am currently a beginner developer working on a few side projects trying to make my way into the world of android java development. My question today however applies to most OOP driven concepts. Let me get to the point.

My Android Application has some activities and methods that end up having very heavy database queries, this makes it quite slow especially because i am using an ORM (SugarORM) to make things faster (Development wise) and less buggy.

I have already found a solution to this and it seems to be working quite well, however, i thought it would be best to ask about it before integrating it through out the application. Just to know if this is generally a bad practice or not.

Unfortunately, google wasn't very helpful, mostly because the keywords needed to search for a similar question would always take me to the Null Object Pattern :|

By Example of my implementation:

private List<Book> mBooks;

public List<Book> getBooks() {
    if (this.mBooks == null)
        this.mBooks = SugarRecord.listAll(Book.class);
    return this.mBooks;
}

public List<Book> onBookListUpdated() {
    this.mBooks = null;
}

As you can see this ensures that the query is only executed once (at least until the list is expected to have changed).

What i would need to know is if this makes sense, how many programmers would actually do something like this and if it is a thing what's it called?

Furthermore if it is 'ok' to do, would it be a good idea to wrap this logic in a class? Say something Like:

public class FastList<T> {

    public interface iFastList<TT> {
        List<TT> reloadList();
    }

    public FastList(iFastList<T> inCallback) {
        this.callback = inCallback; 
    }

    private iFastList<T> callback

    private List<T> currentList;

    public List<T> getList() {
        if (this.currentList == null)
            this.currentList = this.callback.reloadList();
        return this.currentList;
    }

    public void onListChanged() {
        this.currentList = null;
    }

}

Thanks in advanced to all that will take time to answer.

Aucun commentaire:

Enregistrer un commentaire