Short question: is it OK to declare data-object properties as IEnumerable
, or it should be Array
instead?
Background:
I've just found a bug in our project which caused performance issue. The reason was that IEnumerable has been iterated multiple times. But it is simple only at first sight. I think there is a design flaw there which allowed that to happen.
The deeper investigation has shown that one method GetAllUsers
returned a UsersResponse
object, one of the properties of which was IEnumerable<T> UsersList
. When caching was implemented, obviously the entire UsersResponse
object was being cached, and it worked fine at that time because GetAllUsers
assigned an array to IEnumerable<T> UsersList
. Later implementation of GetAllUsers
has changed and for some reason developer decided that ToArray()
call is redundant. So I think the problem was that UsersResponse
object was not well-designed and allowed too much freedom for it's factory-method. On the other hand, caching an object which contains IEnumerable
properties is also useless in principle.
So we return to my question of designing data-objects in general: when you declare it, not knowing if it will be cached some time in the future or how it will be used in other ways except your current need, is it OK to declare it's properties as IEnumerable
, placing the responsibility of careful usage on other developers, or it must be Array
from the start?
What I've searched:
The only suggestion I've found is Jon Wagner's blog post where he recommends to “Seal” LINQ chains as soon as they have been built. But this relates more to building the IEnumerable than storing it in an entity property. Although in conjunction with principle to return as specific type as possible, it can imply declaring property as Array
.