Alex Rivera | Logout

Any problem with doing the main work of a class in its constructor?

Asked 2010-09-29T10:36:06.487
12

I have always felt that in general the main work of a class should be done in its instance methods, while the constructor should only get the instance into a usable inital state.

But I find that in practice there are situations where it seems to make more sense to put essentially all the actual work into the constructor.

One example: I need to retrieve some DBMS-specific information from the database. The most natural way to me seemed to have a class DBMSSpecInfo, with a constructor:

public DBMSSpecInfo(java.sql.Connection conn) throws SQLException{
  // ... retrieve info from DBMS
}

/** @returns max size of table in kiB */
public int getMaxTableSize() {//...}

/** @returns max size of index in kiB */
public int getMaxIndexSize() {//...}

/** @returns name of default schema */
public String getDefaultSchema() {//...}

You would construct the class once, the constructor would fetch all data, then you could use various getters to retrieve the info you need.

Of course I could put the method somewhere else, and only use DBMSSpecInfo for the return value (essentially using DBMSSpecInfo only as a value holder), but it feels ugly to create a class just for returning values from a single function.

So what do you think? Are there problems with performing the main work in the constructor? Is it "un-idiomatic" in Java? Or is it an acceptable (though possibly uncommon) practice?

Edit
Report

1 Answer

1

Just be careful that the object is not cloned/deserialised. Instances created this way do not use the constructor.

answered 2010-09-30T05:37:52.763

Your Answer