Question

This might sound like a noob question.

class MyClass
{
    public List<MyObjects> myObjects;

    public MyClass()
    {
        //...
    }
}

class UserClass
{
    public void SomeFunction()
    {
        MyClass obj = new MyClass();

        //Should this belong in constructor of MyClass?
        obj.myObjects = new List<MyObjects>;

        //Should 'SomeFunction' initialize obj.myObjects before using it, or 
        //should it assume it has been initialized and just use it?
        obj.myObjects.Add(..);
    }
}

Who is responsible for creation / initialization of MyClass.myObjects, when the default constructor is invoked?

  1. Constructor of MyClass.
  2. User of MyClass.
Was it helpful?

Solution

In general, the constructor of a class should do all work necessary for that class to be in a usable state. In your case here, you should probably provide an accessor method for myObjects. The principles of OOP say to encapsulate data. That means that myObjects should be private. You should only have access to it via accessor methods. By doing that, then you can construct the object and lazily create the list via the accessor method when it is actually needed.

Here is a wiki article dealing with Constructors. It mentions that a properly written constructor will leave the object in a valid state.

EDIT: Encapsulated myObjects with lazy initialization (Note I am assuming C# since your code sample looks kind of like that)

class MyClass
{
    private List<MyObjects> myObjects;

    public MyClass()
    {
        //...
    }

    public void Add(MyObject object)
    {
        MyObjects.Add(object);
    }

    private List<MyObjects> MyObjects
    {
        get
        {
            if (myObjects == null)
            {
                myObjects = new List<MyObject>();
            }
            return myObjects;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top