My class derived from SQLiteOpenHelper is getting huge

后端 未结 5 1078
遥遥无期
遥遥无期 2021-02-19 07:55

My class derived from SQLiteOpenHelper is getting bigger and bigger over a time. At the speaking time it is more than 1500 lines of code which is not considered to

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 08:29

    Yes, the examples shown in the dev. site do encourage the creation of a monster class where you hardcode the names of every table and column. This is a mess. You might want to create a class to handle each table. These classes can act as Data Access Objects for each table.

    This is what I use:

        public interface DataAccessObject {
    
            public void onCreate(SQLiteDatabase db);
    
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
    
            public void create(E... params);
    
            public E[] retrieve(E... params);
    
            public void update(E... params);
    
            public void delete(E... params);
    
        }
    

    Then I code an implementation for each table. The generic tipe E are usually pojos. Notice I'm not mixing the classes intended to just hold data (pojos) with the classes in charge of persisting-retrieving data (DAO's). For instance a pojo could be Car, with its variables (color, year, etc). Then i'd code a CarDAO extending DataAccessObject. And this DAO class is in charge of mapping the pojo's variables to DB columns, querying the table and writting to it.

    Finally, you can have a SQLiteOpenHelper that is injected with the DAOs, and delegates stuff for each table to them. These DAO implementations are the ones having table and column name constants. And they can talk to each other if needed for some complex queries. (Notice how this is also one of the drawbacks of this approach: producing a neat design is not straightforward when you need queries involving many tables and columns).

提交回复
热议问题