List-Based Programming Styles

When designing your applications to expose list-based data, there is a difference between styles of programming.  For instance, suppose you wanted to expose a collection of objects to the consumer.  This could be simply done using the following class:

public class Customer
{
   private List<Order> _orders = new List<Order>();

   public List<Order> Orders
   {
        get { return _orders; }
   }
}

So Customer exposes an Orders property, which is a list of Order objects.  This list can be modified in any way; an item can be added, removed, inserted, or looped through on demand.  This is more of a permissive style of programming with data because anything that can be done with the list can be done directly to it without any inherent restrictions (unless the List<> class imposes any restrictions like not allowing null values, etc.).  The alternative to this approach would more of a restrictive approach, whereby a class controls and somewhat restricts what can be done with the list.  Suppose you had the following class:

public class OrdersList
{
    public void Add(Order order) { .. }

    public IEnumerable<Order> GetAll() { .. }

    public void Remove(Order order) { .. }
}

public class Customer
{
   public OrdersList Orders { .. }
}

In this example, a custom object contains the methods whereby the Customer can retrieve orders.  The customer can only work with the orders if OrdersList supports it (the same restriction that List<> may impose).  Furthermore, it doesn't support iterating against it directly, but rather returns a list that can be enumerated against.  In this way, there is a little more control over how the data gets accessed.  In addition, before you would alter the list directly; in this scenario, the list returned from GetAll() restricts you from being able to alter the list directly.  You can add or remove items from the result returned via GetAll; however, this only affects the view and not the underlying list.

I like this approach too, because it works great in encapsulating the underlying storage structure.  For instance, the data structure may be a list, but it could also be a DataTable.  GetAll() would then convert the table to an Order object.  That may not be the most efficient, but is a possibility.

Comments

No Comments