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.
public class Customer
{
public static ICollection<Customer> FindCustomers()
{
Collection<Customer> customers = new Collection<Customer>();
foreach (CustomerDTO dto in DAL.GetCustomers())
customers.Add(new Customer(dto)); // Do what you need to to create the customer
return customers;
}
}
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 Customer
type) 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 wish CustomerUtility
or CustomerHelper
for example).
My final suggestion is to return an interface type from FindCustomers()
to give you greater flexibility in the future for implementation changes. Obviously DAL.GetCustomers()
would have to return some type that implemented IList<T>
as well but then any API method (especially in a different tier like a data layer) should be returning interface types as well.
In my opinion both of them are a bit weird and confusing. When you extend the Collection class you kind of imply that your class IS a collection - so that it contains the data. I think when you make this method static in the first case it will make the most sense:
public class Customercollection: Collection<Customer>
{
public static Collection<Customer> FindCustomers()
{
//calls DAL and gets a Collection of customers
Collection<Customer> customers = DAL.GetCustomers();
return customers;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With