I tried to find a similar question on SO, but no luck. Sorry if this is a duplicate.
What are the disadvantages of instantiating class type variables when they are declared?
In many of the classes that represent the Business Object Model, we have these things:
public class RateArea {...} public class FlatRateSchedule { public string ScheduleID {get;set;} public decimal MaxAmount {get;set;} } public class PricingData { private List<RateArea> rateAreaList = new List<RateArea>(); private FlatRateSchedule flatRateSchedule = new FlatRateSchedule(); public List<RateArea> RateAreaList { get { return rateAreaList; } set { rateAreaList = value; } } public List<FlatRateSchedule> FlatRateScheduleList { get { return flatRateScheduleList; } set { flatRateScheduleList = value; } } }
At some point, this PricingData class is initialized, and some properties are hydrated (but not always all properties).
The idea is that we create "empty" class instances so that no properties are ever null . This is convenient because we never need to check if any property is null before accessing them. Whether the properties are hydrated or not, they will never be βnullβ for the class of consumption. If the properties are not initialized, then the code should check for null each time before accessing the property.
Is the blanket convention that "all class properties should be initialized at all times and should never be null" is really bad?
Besides using some resources to instantiate the default class, the cost savings in the code for checking exception exceptions seem to be worth it. Are we missing something?
source share