Tuesday, June 22, 2010

Return read-only collection if you want to control its modification

Let's review the following example:
public class Order
{
private List _orderItems = new List();

public ReadOnlyCollection OrderItems
{
get { return _orderItems.AsReadOnly(); }
}

public void AddOrderItem(OrderItem orderItem)
{
...
_orderItems.Add(orderItem);
}
}

The class has a public property of a collection type and I want to have “controlled access “to this collection. What I mean is, that a consumer of these classes should not to add an OrderItem to the collection directly . since some additional actions need to be executed. He should always use the AddOrderItem method id he wants to add an OrderItem To the Order.

In Such cases keep the collection private, create the necessary methods to provide the necessary controlled access to the collection and create a public property which returns a read-only instance of the collection. So that you can iterate through the collection, change existing instances of objects within the collection, get the number of objects that are in the collection etc

No comments:

Post a Comment