2

Looking through some of our business logic code I've found where some methods are being passed an un-executed IEnumerables as a parameters such as this:

GetDetails(IEnumerable <Entity> item) { // do something with the item }

Now the code works fine as is, but what I'm seeing when I'm in debug is that the parameter is passing a raw query, not a collection of anything. To me this seems a little wrong since you could be hitting the database every time that this IEnumberable is used if the query is pointed at a database.

So what i'm asking, is passing an un-executed IEnumerable as a parameter to a method bad practice?

After more investigation

I've read around more on stackoverflow, and found this particular question where Eric Lippert says:

Remember, a query expression gives you an object which represents the query itself. The object does not represent the RESULTS of the query, the object represents a query. Think of it as a SQL query string, only smarter. You ask the query for its results, and the query executes. You ask it again, the query executes again; no guarantees that the results are the same the second time you ask; the world might have changed since then

To me, this seems to say that if you're going ot use a defered query such as an IEnumberable, to be careful where you use it, and when you use as you might not get the results which are expected. But further into the answers I see that Bevan says he personally does this:

Parameters to methods - use IEnumerable unless there's a need for a more specific interface.

So my question still stands, is passing an un-executed IEnumerable as a parameter to a method bad practice or should I not care about the when the data is requested, just that it is requested.

Community
  • 1
  • 1
Chris
  • 6,272
  • 9
  • 35
  • 57
  • Remember that `IEnumerable/IEnumerable` as an interface and the deferred execution of `yield` are two different things. @Bevan is presumably talking about the general advice to return the lowest-common-denominator interface, which is quite different from deferred execution. One certainly needs to be careful with deferred execution in some cases. – nicodemus13 Sep 18 '12 at 14:49

1 Answers1

2

Once the data leaves the business logic layer, it should IMHO be a hard collection that is no longer connected to the database. Passing a collection between methods in the Business Logic should be ok because you may want to add criteria/filtering to your query without loading the entire data set from the database.

mellamokb
  • 56,094
  • 12
  • 110
  • 136