HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

When to initialize infrequently used base class objects

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
objectsusedinfrequentlywhenclassinitializebase

Problem

I have a business object base class which is inherited by my business objects:

public class ErrorBase
{
    public bool HasError { get; set; }
    public List ErrorList { get; set; }

    public ErrorBase()
    {
        HasError = false;
        ErrorList = new List();
    }
}


Can this be optimized? My concern is that List is initialized every time a business object is instantiated, regardless of whether an Error object is ever added.

The only alternative I can think of is initializing ErrorList = null, then checking ErrorList != null before calling ErrorList.Add(), but I'm not sure that performing that check every time before adding an Error is actually an optimization. It certainly adds steps to the process of adding an Error object to the List<>.

Is there another way I'm not thinking of? If not, is one of these approaches considered a best practice?

Solution

First: I doubt that creating a new List<> object creates enough overhead which has measurable impact on your system so unless you can prove that it's a problem don't worry about it.

That being said: The classic solution to that problem is lazy instantiation. As you have a property already this can be easily achieved by:

public class ErrorBase
{
    public bool HasError { get; set; }

    private List _ErrorList = null;
    public List ErrorList
    {
        get
        {
            if (_ErrorList == null)
            {
                _ErrorList = new List();
            }
            return _ErrorList;
        }
    }

    public ErrorBase()
    {
        HasError = false;
    }
}


If you have multiple threads adding to it then you need to add some locking in the get - but then on the other hand List<> itself is not thread-safe so I assume that's not the case.

In .NET 4.0 and later you have Lazy<> which will make the code a little bit shorter.

Code Snippets

public class ErrorBase
{
    public bool HasError { get; set; }

    private List<Error> _ErrorList = null;
    public List<Error> ErrorList
    {
        get
        {
            if (_ErrorList == null)
            {
                _ErrorList = new List<Error>();
            }
            return _ErrorList;
        }
    }

    public ErrorBase()
    {
        HasError = false;
    }
}

Context

StackExchange Code Review Q#38961, answer score: 4

Revisions (0)

No revisions yet.