I would like to know what is the best pattern when returning objects from custom collection classes. To illustrate my problem, here is an example:
I have a Customer class:
public class Customer
{
//properties
//methods
}
Then I have a customer collection class:
public class Customercollection: Collection<Customer>
{
public Collection<Customer> FindCustomers()
{
//calls DAL and gets a Collection of customers
Collection<Customer> customers = DAL.GetCustomers();
return customers;
}
}
Now, an alternative version of this method can be:
public class Customercollection: Collection<Customer>
{
public Collection<Customer> FindCustomers()
{
//calls DAL and gets a Collection of customers
Collection<Customer> customers = DAL.GetCustomers();
foreach(Customer c in customers)
this.Add(c);
return this;
}
}
I would like to discuss Which one is the better approach? And is there any other approach better than two above two?
I would propose a third approach:
Edit: I have updated this code example to reflect the OP’s comments below.
Most of the time a custom collection is not needed – I am assuming that this is one of those cases. Also you can add utility methods onto the type (in this case, the
Customertype) as this aids developer discovery of these methods. (This point is more a matter of taste – since this is a static method you are free to put it in whatever type you wishCustomerUtilityorCustomerHelperfor example).My final suggestion is to return an interface type from
FindCustomers()to give you greater flexibility in the future for implementation changes. ObviouslyDAL.GetCustomers()would have to return some type that implementedIList<T>as well but then any API method (especially in a different tier like a data layer) should be returning interface types as well.