Monday, September 14, 2009

Early creation of public properties

I’m battling myself a bit about a public API I’m writing. Should I initialize all my public properties in the default constructor, or should I initialize them when accessed?

Having a public property returning null is not an option in my opinion as it leads to extra checking on the consumer of the API. Grunt work which the API should do for you.

Consider the two following classes:

public class MyClass
{
public List<string> List { get; set; }

public MyClass()
{
List = new List<string>();
}
}

and

public class MyClass
{
private List<string> _list;
public List<string> List
{
get
{
if( _list == null )
{
_list = new List<string>();
}
return _list;
}
set { _list = value; }
}

public MyClass()
{
}
}


The pros for the first class is that it’s short and very easy to read. The pros for the second class is that it is more optimized in terms of memory usage if the property is not always used.

My API has an object structure of about 20 classes, which may or may not be set. Some might be used more frequent and favor the first class, as others are infrequent and would favor the last one.

Having both implementations seems a bit inconsistent, so the big question is; should I favor the easy read, or the optimized? If the object structure is being created often, will creating all these extra objects be bad for the clr or doesn’t it matter?

It might be that benchmarking is the way to go to give the final answer, but any comments on the matter is appreciated.