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.

Bruusi Post By Bruusi
8:53 AM
20 Mar 2006

Comments:

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

Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above