Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

8. Classes in the .NET Framework > Constructing Constructors

Constructing Constructors

Best practice dictates that constructors should do very little. In fact, most well-designed constructors only set the class properties to their initial values using the property accessors to ensure that any necessary validation takes place.

The reason you should use the property accessors is so that you don’t duplicate code. Duplicating code is always bad. (Or at least, in all my years of programming I’ve never seen a good reason to do it. If you think of one, email me.) And it applies to constructors just as much as it applies anywhere else in an application.

There’s a conflict here: On the one hand, it’s a kindness to the users of your class to be able to set only the basic properties of the object when it’s instantiated, and that usually means several overloads of the constructor. On the other hand, you don’t want to duplicate the code that sets those properties within the various method calls. The solution is to use a design pattern called CONSTRUCTOR CHAINING: the versions of the constructor with fewer parameters call the versions with more, providing reasonable defaults for the missing arguments:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint