Skip Navigation LinksHome > View Post

Initialisation using constructors

In this article I am going to discuss the advantages of class initialisation using Constructors. Quoting Wikipedia's page on constructors: "a properly written constructor will leave the object in a valid state".

I am going to use VB.NET as an example because I've seen a lot of this kind of thing lately:

Dim someObject as New SomeObject

With someObject
.SomeProperty = SomeValue
.OtherProperty = OtherValue
.AnotherProperty = AnotherValue
End With

In this case, the three properties above are mandatory for this class to be of any use, or, valid. In this case I would always plump for a constructor to enforce this constraint:

Dim someObject as New SomeObject(SomeValue, OtherValue, AnotherValue)

Why? What are the benefits?

Firstly, it clearly indicates to anybody else who has to work with your class (team mates etc) what the requirements are.

Secondly, you get compile-time errors rather than run-time errors (though don't forget to add guard clauses to check for nulls and throw an ArgumentNullException). This is particularly useful if, somewhere in the middle of your project, you realise your class needs a fourth value to be in a valid state. Simply add an extra parameter to your constructor and the compiler will point out all the places you need to provide extra information.

It's the programming equivalent of defensive driving.

Tags: .NET

 
Bruusi Post By Bruusi
8:53 AM
20 Mar 2006

» Next Post: Tuning the ThreadPool
« Previous Post: Visual Notepad2

Comments are closed for this post.

Posted by Colby @ 18 Jul 2008 12:54 PM
Agreed.

Posted by Tim @ 24 Jun 2011 9:34 AM
Indeed, also you don't need a public property for each member variable you are wanting to initialise, this adds further benefits:
tighter control over what a caller can change (set) post object construction.
a smaller memory footprint

On the other hand classes with a lot of constructor overloads can get very difficult to use and indeed write/maintain.

© 2005 - 2014 Josh Twist - All Rights Reserved.