Java Constructors


Performance and scalability: Java Constructors

  1. Java Constructors (3 messages)

    Iam instantiating a class by accessing a database to construct an instance variable, is this approach right?.
    I make a call to db from the constructor of the class...

    Threaded Messages (3)

  2. Java Constructors[ Go to top ]


    I think this could be OK under some circumstances:

    The environment using your class should know how to react if the database cannot be accessed.

    Thus the constructor should throw an exception.

    If your class urgently needs data from a db to exist it is OK to get the data in the constructor from the database.

    As an alternative the data could be get in a method of the class. But then you have to handle all those cases in which the object is accessed and hasn't been initialized.

    Another alternative could be that a DataBaseAccessor-class gets the data and you construct your object with this data.

    You should decide who should know about the data and who should have a connection to the db.

  3. Java Constructors[ Go to top ]

    Or create an overloaded constructor that triggers the database load in order to remove any ambiguity. This way developers can choose the style of loading they require (eager or lazy):

     public class MyClass
       public MyClass() {}

       public MyClass(boolean load) {
         if(load) {

       public void loadData(){}

  4. Java Constructors[ Go to top ]

    From design point of view it would be better to create and populiate your class instance by other party (builder, factory). In your case you coupling your domain classes with persistence logic.