Dinesh recent post, Lazy ORM users deserve it!, talks about how lazy loading can lead to performance and concurrency problems. I’m slowly coming to the conclusion that lazy loading is the root of all that people see as evil when it comes to O/R Mappers. By hiding the loading of objects from a data store behind a lazy loaded property we make the cost hidden to the end user who is utilizing our objects. It might be known that lazy loading leads to additional database hits, however, often times the scope and depth of database interaction that can result from lazy loading is not fully realized.
Many O/R Mappers support eager fetching of related objects to help reduce the amount of database interaction that is required for loading objects which are known to be required for a particular set of domain logic (See Ayende Combating the SELECT N + 1 Problem). In additional to supporting eager fetching some mappers have a caching layer that helps reduce the amount of database interaction necessary for loading the data you need. Often times it isn’t enough to prevent an innocent looking set of domain logic from causing an explosion of database hits.
So the question is...do we need to get better at using our O/R Mappers efficiently, or should our O/R Mappers make us be explicit about what we want them to retrieve and do away with lazy loading? What’s your take?
* By the way this problem isn’t unique to O/R Mappers