Encapsulate Collection refactoring with generics

Encapsulate Collection is a refactoring from Martin Fowler’s book Refactoring: Improving the Design of Existing Code, the refactoring is applied when you have a class with a public property of a collection type, the intent is to stop the collections internal data structures from being exposed.

I was thinking about how to apply this refactoring using .NET 2.0 and generics and decided on the implementation below;

public class Order
{
private List<IOrderLine> _orderLines;

public ReadOnlyCollectionList<IOrderLine> OrderLines
{
get { return _orderLines.AsReadOnly(); }
}

public Order()
{
_orderLines = new List<IOrderLine>();
}

public void AddOrderLine(IOrderLine orderLine)
{
_ orderLines.Add(orderLine);
}

}

The generic ReadOnlyCollection Class provides a base class for a generic readonly collection, using this class as opposed to the generic IList, has the advantage that someone implementing the class can see at design time that the class is readonly; however the generic IList may be a better alternative as more of collections internal data structure is hidden: any thoughs on this would be much appreciated.
Refactoring: Improving the Design of Existing Code

Bookmark on del.icio.us

Leave a Comment