Akg
Akg

Reputation: 359

querying database in constructor (java)?

Is it a good practice to execute query in constructor?

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

  private void populateData() {
    // query database here...
  }
}

Upvotes: 5

Views: 2260

Answers (3)

Julio
Julio

Reputation: 718

You could use lazy values. Google Guava provides some utilities to do that.
e.g.

class Foo {

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

  public Foo() {

  }
}

Upvotes: -1

ekostadinov
ekostadinov

Reputation: 6940

If you want your code to be both legible and extensible, I can advise to consider the Single_responsibility_principle. According to it - every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.

So bottom line is your method to be put to work like this:

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

Upvotes: 0

meda
meda

Reputation: 45490

Constructor only purpose is to create an instance of a class.

The issue with querying a database is the operation can fail.

At that point if you don't handle exception properly then your code is candidate for bugs.

You should think of constructor a way to prepare the object for use which should be quick.

Upvotes: 8

Related Questions