Stephen Holt
Stephen Holt

Reputation: 2368

Construct object in base class constructor?

I currently have the following code pattern, where I am initialising a particular object of type MyThing in the constructor of the general class MyClass. However, in some specific derived class examples (e.g. MySpecialClass), I want to use a derived version of MyThing, which I have called MySpecialThing.

public class MyClass
{
    public MyClass()
    {
        this.MyThing = new MyThing();
    }

    public MyThing MyThing { get; set; }
}

public class MySpecialClass : MyClass
{
    public MySpecialClass()
    {
        this.MyThing = new MySpecialThing();
    }
}

My question is whether this is bad practice because in effect the MyThing property is being initialised twice, once in the base class and once in the derived class. Obviously I could pass in a boolean to the base class constructor or something to tell it not to bother initialising MyThing, but that might be overkill...

Upvotes: 0

Views: 347

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109852

It depends how much overhead there is for creating MyThing.

However, there is a solution:

You can add a protected base class constructor which accepts a parameter of type MyThing, and initialise it there.

public class MyClass
{
    private readonly MyThing myThing;

    public MyClass(): this(new MyThing())
    {
    }

    protected MyClass(MyThing thing)
    {
        Contract.Requires(thing != null);
        myThing = thing;
    }

    public MyThing MyThing { get { return myThing; } }
}

public class MySpecialClass : MyClass
{
    public MySpecialClass(): base(new MySpecialThing())
    {
    }
}

I think this is a better approach than adding a bool to a public base class constructor.

I also think this is worth doing even if there is very little overhead to constructing a MyThing, because it much more clearly expresses the design.

I've also changed the design slightly to make myThing a readonly field, to express the intent that it should only be set at construction time. (If that's not the case and you want it settable later on, you will have to revert to a public property setter.)

Upvotes: 5

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

Are you concerned with performance or maintainability?

The performance issue would only make sense if MyThing constructor is expensive, or you have to create a lot of objects in tight loop.

I would be more worried about maintainability as you have multiple places where the object state is initialized. You could pass it to a protected base class constructor from derived class, and have a default constructor which uses MyThing by default

Upvotes: 1

David
David

Reputation: 16287

Use protected:

class BaseClass
{
    protected SomeType MyThing;
}

Upvotes: 0

Related Questions