3.21. Preventing the Creation of an Only Partially Initialized Object
Problem
You need to force a client to use an overloaded constructor, which accepts parameters to fully initialize the object, rather than a default constructor, which may not fully initialize the object. Often a default constructor cannot fully initialize an object since it may not have the necessary information to do it. Using a default constructor, the client is required to perform a multistep process; for instance, create the object and then initialize its fields either through various properties and/or methods.
Solution
By removing the default constructor
and strictly using parameterized constructors, the client is forced
to provide the necessary initialization parameters during object
creation. The following Log
class will not
initialize its LogStream
field to a
StreamWriter
object on
construction:
public class Log { private StreamWriter logStream = null; public StreamWriter LogStream { get {return (logStream);} set {logStream = value;} } // use the LogStream field... public void Write(string text) { logStream.Write(text); } }
The C# compiler will automatically create a default constructor that calls the default constructor of its base class, if you omit the constructor for a class. The following modified class will prevent the default constructor from being created:
public class Log { public Log(StreamWriter logStream) { this.logStream = logStream; } private StreamWriter logStream = null; public StreamWriter ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.