IEnumerable could be considered harmful…

… well, of course only under certain circumstances, but hey, I am quite experienced developer, and today I once again wrote code that killed app in unexpected way. So the point of this post, do not undervalue lazy nature of the IEnumerable. Or do not use IEnumerable as arguments in your API. Both is OK.

Later is explanation for idiots like me. So take a look on this code:

Simple LINQ query and simple usage of the results. Problem comes when you start using results. This is very easy to write code that will re-evaluate your nice LINQ stuff again and again. And this very easy to introduce unexpected side-effect. And this quite hard to find this side-effect.

In my case I have had quite large LINQ query, that among other things called method that was responsible to find some entity and if not found, create it. And query was evaluating six! times for each item. As the result six new records in database, every time I hit this code. After I figure out what is wrong, fix was an easy job. However I still really ashamed with this code.

From now I think to try arrays. This is does not seem to kill API usability, and even looks more compact. That’s it. Hope you do not write such stupid code.

. .