When I\'m writing my DAL or other code that returns a set of items, should I always make my return statement:
public IEnumerable GetRecentItems
I think you can use either, but each has a use. Basically
List
isIEnumerable
but you have count functionality, add element, remove elementIEnumerable is not efficient for counting elements
If the collection is intended to be readonly, or the modification of the collection is controlled by the Parent
then returning an IList
just for Count
is not a good idea.
In Linq, there is a Count()
extension method on IEnumerable
which inside the CLR will shortcut to .Count
if the underlying type is of IList
, so performance difference is negligible.
Generally I feel (opinion) it is better practice to return IEnumerable where possible, if you need to do additions then add these methods to the parent class, otherwise the consumer is then managing the collection within Model which violates the principles, e.g. manufacturer.Models.Add(model)
violates law of demeter. Of course these are just guidelines and not hard and fast rules, but until you have full grasps of applicability, following blindly is better than not following at all.
public interface IManufacturer
{
IEnumerable Models {get;}
void AddModel(Model model);
}
(Note: If using nNHibernate you might need to map to private IList using different accessors.)