views:

72

answers:

3

Is it a good practice to call methods from constructors?

+1  A: 

I sometimes put an init() call in the constructor of my objects if I have lots of other overloaded versions of the constructor that need to initialize the class in the same way. It's DRY.

jskaggz
+1  A: 

I assume you are talking about other private/public functions of the class which is being initialized.

Like anywhere else, I would say decomposing large complicated behavior into sub functions is good practice.

The obvious complication would be calling functions which rely on as-yet un-initialized content of the object.

Since the constructor and the other functions are in the class have the same visibility (from a code maintainability point of view) I don't think it is unreasonable to say that it is ok to leverage other functions but necessary for the programmer to ensure that such circular dependencies are avoided (like virtual functions).

Akusete
A: 

Not if those methods are virtual. Anyway, just be sure that if your constructor fails (or one of the methods it calls fails) that your constructor does a "catch" to perform a Dispose() on any IDisposables it allocated.

Brent Arias
...and don't forget to re-throw the exception.
Brent Arias
Thanx for the answer guys.The reason why i've asked this question is framework design guidelines book says that constructor should be as simple as possible should only be used for initializing purpose.But what if I have to set some properties from database while creating an instance of the class.If I have a project class.I want to create instance of class passing a projectid parameter into class construtor like Project proj = new Project(projectid);then I want to check proj.HasForecasts property. which is set from database. can I set this property by calling a method from constructor
Yes, you could do that work in a constructor, though I might consider using a static "Create" method on the Project class instead.
Brent Arias