tags:

views:

31

answers:

1

Hi,

I'm again in the position to figure a way out to handle lists with subsidiary objects on our business objects.

Actually, our code often looks like this:

public class Object
{
    private List<SubsidiaryObject> subsidiaryObjects = null;
    public List<SubsidiaryObject> SubsidiaryObjects
    {
        get
        {
            if (this.subsidiaryObjects == null)
            {
                this.subsidiaryObjects = DBClass.LoadListFromDatabase();
            }

            return this.subsidiaryObjects;
        }

        set
        {
            this.subsidiaryObjects = value;
        }
    }
}

The Con on this:

  • The property is referenced in presentation layer and used for DataBinding. Releasing the reference to the actual list and replacing it with a new one will end in an referenced list in the GUI that does not have anything left with the list on the object.

The Pro on this:

  • Easy way of reloading the list (just set the reference to null and then get it again).

I developed another class that uses the following pattern:

public class Object2
{
    private readonly List<SubsidiaryObject> subsidiaryObjects = new List<SubsidiaryObject>();
    public List<SubsidiaryObject> SubsidiaryObjects
    {
        get
        {
            return this.subsidiaryObjects;
        }
    }

    public void ReloadSubsidiaryObjects()
    {
        this.SubsidiaryObjects.Clear();
        this.SubsidiaryObjects.AddRange(DBClass.LoadListFromDatabase());
    }
}

Pro on this:

  • Reference is continous.

The Con on this:

  • Reloading the list is more difficult, since it just cannot be replaced, but must be cleared/filled with reloaded items.

What is your preferred way, for what situations?

What do you see as Pro/Con for either of these to patterns?

Since this is only a general question, not for a specific problem, every answer is welcome.

+2  A: 

Do you need the caller to be able to modify the list? If not you should consider returning IEnumerable<T> or ReadOnlyCollection instead. And even if you do, you will probably be better off making cover versions for Add/Remove so you can intercept modifications. Handing a reference to internal state is not a good idea IMO.

A third option would be to go with option 2, but to create a new instance of the Object2 type each time you need to repopulate the list. Without additional context for the question, that is the option I would select, but there may be reasons why you would want to hold on to the original instance.

Brian Rasmussen
Indeed, the main reason to hold the original instance is, it is an subsidiary object itself... with exception on the top-level.
BeowulfOF