I have a class that provides methods for working with a database, and this is the only class that works with the database in the program:
public class ForwardersHelper { private DBHelper dbHelper; private SQLiteDatabase db; ... ... ... public void addForwarder(Forwarder forwarder) { ... ... ... } public void deleteForwarder(int forwarderId) { ... ... ... } public void changeForwarder(Forwarder forwarder) { ... ... ... } public ArrayList<Forwarder> getForwardersList() { ... ... ... } public int getFreeForwarderId() { ... ... ... } } I have two options for initializing the connection to the database: make everything static and access the class without instances or open the connection, using appropriate methods:
Option 1:
public class ForwardersHelper { private static DBHelper dbHelper; private static SQLiteDatabase db; public static void init(Context context) { dbHelper = new DBHelper(context); db = dbHelper.getWritableDatabase(); } @Override //Во время уничтожения объекта уборщиком мусора, закроются все подключения, так //как этот метод вызывается автоматически public void finalize() { db.close(); dbHelper.close(); try { super.finalize(); } catch (Throwable e) { e.printStackTrace(); } } ... ... ... } When starting the program in the activity or Application class, call the ForwardersHelper.init(this) method. Since static methods are initialized once and for all, such a call will open a connection to the database and work with the methods will be available throughout the program.
Option 2:
public class ForwardersHelper { private DBHelper dbHelper; private SQLiteDatabase db; public void openDBConnection(Context context) { dbHelper = new DBHelper(context); db = dbHelper.getWritableDatabase(); } public void closeDBConnection(Context context) { db.close(); dbHelper.close(); } ... ... ... } Then, after creating each instance, call openDBConnection() , and after using it, call closeDBConnection() .
I tend to the first option, because it is more convenient to use, less code will be obtained in other classes and the code will be clearer, but the code will become a little more difficult to understand and I have doubts about the correctness of finalize() . The second option is clearer for those who read it, but it will become a bit more and lose expressiveness. Which option will still be more correct and why?