Written October 10, 2007 at 08:14 MDT Tagged programming
I see lots of code bases throwing IList
Here is a common example, a service layer method call that returns a list of DTO's that can be consumed by some sort of binding target. Assume that you are mapping domain objects into DTO's to be consumed by the upper level layer (which could then be mapped into a presentation model). Let's also assume that you have the following
Here is the CustomerTask class with its appropriate dependencies injected, and the existing GetAllCustomers method using the temporary list:
public interface ICustomerDTOMapper
{
CustomerDTO MapFrom(Customer customer);
}
public interface ICustomerRepository
{
IEnumerable<Customer> All();
}
public class CustomerTask
{
private ICustomerRepository customerRepository;
private ICustomerDTOMapper customerDTOMapper;
public CustomerTask(ICustomerRepository customerRepository,ICustomerDTOMapper customerDTOMapper)
{
this.customerRepository = customerRepository;
this.customerDTOMapper = customerDTOMapper;
}
public IEnumerable<CustomerDTO> GetAllCustomers()
{
IList<Customer> results = new List<Customer>();
foreach (Customer customer in customerRepository.All())
{
results.Add(customerDTOMapper.MapFrom(customer));
}
return results;
}
}
With a small change the code in the GetAllCustomers method can be changed to the following:
public IEnumerable<CustomerDTO> GetAllCustomers()
{
foreach (Customer customer in customerRepository.All())
{
yield return customerDTOMapper.MapFrom(customer);
}
}
This is a small change, but handy nontheless. Again, this is not new information, I just think that more people could start taking advantage of yielding in more situations where full blown lists are not called for.