Database query in constructor (java)?

Is it good to execute the query in the constructor?

class Foo {
  public Foo() {
    populateData();
  }

  private void populateData() {
    // query database here...
  }
}
+4
source share
3 answers

The purpose of the constructor is to instantiate the class.

Problem with database query - operation may fail.

At this point, if you handle the exception incorrectly, your code is a candidate for errors.

You should think of a constructor to prepare an object for use, which should be fast.

+7
source

, , Single_responsibility_principle. - (, , ..) . .

, - , :

public static class DbAccessor
{
    public static void setPopulatedData() {
        // query database here...
      }
}
0

You can use lazy values. Google Guava provides some utilities for this.
eg.

class Foo {

    private final Spplier<Data> data = Suppliers.memoize(new Supplier<Data>() {
  public Data get() {
    // query database here...
    return data;
  };
});

  public Foo() {

  }
}
0
source

All Articles