Cylindric
Cylindric

Reputation: 5894

Heavy Constructors or use a method

Both of these methods are kind of working for me, but I'm not sure what the recommendation would be from a "good practice" point of view.

I have a class which performs various control functions within my library, so needs to initialise all sorts of objects and properties.

Is it okay to put all this logic in the constructor for the class, or should I put it in an "Initialise" method.

public MyClass()
{
    mSubObjectA = new mSubObjectA();
    mSubObjectA.DoStuff();
    mSubObjectA.DoMoreStuff();

    mSubObjectB = new mSubObjectB();
    mSubObjectC = new mSubObjectC();

    if (something)
    {
        DoStuff();
    }
    else
    {
        MagicHappens();
    }
}

Upvotes: 3

Views: 927

Answers (3)

John
John

Reputation: 2792

It depends on how many constructors you think you will have. Don't repeat code. If all of these steps will only happen in your one constructor, it's not a problem. If you're looking to do something more fancy, intelligently arrange your code.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500105

Personally I like an object to be fully operational by the time I receive it. On the other hand, doing a lot of work in the constructor does smell somewhat.

One alternative is to write a static factory method (or a factory class*) which can do all the work it needs to before calling the constructor, and then make the constructor itself pretty straightforward. You can choose to expose the simple constructor or not, depending on your requirements.

* A factory class can make for better testability, and allows for potentially different factory implementations. On the other hand, at that point you've got a pretty hefty level of abstraction going on, which can be a distraction.

Upvotes: 7

Oded
Oded

Reputation: 498952

There is an alternative to both - use a factory class or factory method.

Constructing complex object graphs is what the factory pattern is about - sounds like a very good fit to your situation.

Upvotes: 1

Related Questions