I am currently coding a simple Data Access Layer, and I was wondering which type I should expose to the other layers.
I am going to internally implement the Data as a List<>, but I remember reading something about not exposing the List type to the consumers if not needed.
public List<User> GetAllUsers() // non C# users: that means List of User :)
Do you know why (google didn’t help)? What do you usually expose for that kind of stuff? IList? IEnumerable?
Usually it’s best to expose the least powerful interface that the user can still meaningfully work with. If the user just needs some enumerable data, return
IEnumerable<User>. If that’s not enough because the user needs to be able to modify the list (attention! shouldn’t often be the case), return anIList<User>./EDIT:
Joel asks a valid question in his comment: Why indeed expose the least powerful interface instead of granting the user maximum power? (paraphrased)
The idea behind this is that the method returning the data might not expect the user to modify its content: Another method of the class might still expect the list to be non-empty after a reference to it was returned. Imagine the user removes all data from the list. The other method now has to make an additional check that ele might have been unnecessary.
More importantly, this exposes parts of the internal implementation through the return type. If I need to change the implementation in the future so that it no longer uses an
IListcontainer, I have a problem: I either need to change the method contract, introducing a build-breaking change. Or I need to copy the data into a list container.As an example, imagine that an efficient implementation uses a Dictionary and just returns the
Valuescollection which doesn’t implementIList.