When/Where to create a new object of my class that communicates with the Database

Viewed 40

So I think I pretty much covered it in the Subject. But say I have a Class that communicates with the SQLite database. Methods like addInfo, fetchInfo and what have you, I am calling this class App.java (is this the right name for the Class that communicates with the DB?).

Pseudo-code for App.java:

public class App{
    public void addInfo(String info){
        INSERT INTO table VALUES(info)
    }

    public String fetchInfo(){
        SELECT info FROM table
        return stringWithInfo;
    }
}

now, When I want to use the App.java in another class, should I create a new App object for each method that uses it?

public class AnotherClass{

    public void methodOne(){
        App a = new App();
        String containingInfo = "Frogs quack";
        a.addInfo(containingInfo);
    }

    public void methodTwo(){
        App a = new App();
        System.out.println(a.fetchInfo());
    }
}

Or should I create a new class-wide object?

public class AnotherClass{

    App a = new App();

    public void methodOne(){
        String containingInfo = "Frogs quack";
        a.addInfo(containingInfo);
    }

    public void methodTwo(){
        System.out.println(a.fetchInfo());
    }
}

What is best practice? And why?

0 Answers
Related