If an object has a property that is a collection, should the object create the collection object or make a consumer check for null? I know the consumer should not assume, just
You can also use the "Lazy initailizer" pattern where the collection is not initialized until (and unless) someone accesses the property getter for it... This avoids the overhead of creating it in those cases where the parent object is instantiated for some other purpose that does not require the collection...
public class Division
{
private int divId;
public int DivisionId { get; set; }
private Collection emps;
public Collection Employees
{ get {return emps?? (emps = new Collection(DivisionId));}}
}
EDIT: This implementation pattern is, in general, not thread safe... emps could be read by two different threads as null before first thread finishes modifying it. In this case, it probably does not matter as DivisionId is immutable and although both threads would get different collections, they would both be valid. Whne the second thread fihishes, therefore, emps would be a valid collection. The 'probably' is because it might be possible for the first thread to start using emps before the second thread resets it. That would not be thread-safe. Another slightly more complex implementation from Jon SKeet is thread-safe (see This article on SIngletons for his example/discussion on how to fix this.