Best practices when using constructors

When it comes to constructors, I always suggest not using any code in the constructor except the code that initializes local members. All other code could possibly throw an exception. Use only the constructor to pass the parameters to its local members. The reason behind this is, when an exception occurs, the calling party retrieves a null pointer. This misuses the main purpose of a constructor, namely allocating memory and returning a pointer to the new created instance.

Also there is a possibility to leak memory. This occurs mainly in unmanaged languages such as C++. But also even in C# you can run into scenario’s where memory is leaked. Think of C# which calls unmanaged code. The reason behind this is, when an exception is thrown from within the constructor, the destructor will not be executed. Specially when you already allocated memory before the exception occurred, this memory is not freed any more.

How could you initialize code then? One of the strategies is to use an “initialize” member. The calling party should call initialize first in order to prepare the instance of the object. Drawback of this strategy is that public members should be programmed in a defensive way that they check if the instance is initialized.

public class MyClass
{
   public MyClass() { }

   public bool Initialize()
   {
     if (!m_initialized)
     {
       m_initialized = true;
     }

     return m_initialized;
   }

   public void DoSomething()
   {
     if (m_initialized)
     {
       ...
     }
   }
   private m_initialized = false;
}

Another way to initialize code is by using the Factory Pattern. By calling a “createInstance” a new instance is created and code is initialized:

public class MyClass
{
   public static MyClass CreateInstance()
   {
     MyClass newClass = new MyClass();
     newClass.Initialize();
     return newClass;
   }
}
Posted in Best practices by Bruno at March 12th, 2014.

Leave a Reply