In previous posts I've written about how I believe being lazy makes me a better programmer. Today I'm going to talk about how using lazy objects can have a counter affect. In many of the applications that I write I have properties that are lazy loaded. A lazy loaded property starts out as null, and upon the first access to the property the value is retrieved from the data store. This can help reduce the load on the database server and can help ensure we only access the data that is necessary.
If your not careful with lazy loaded properties you can quickly run into trouble. This past week I was investigating a performance problem in a section of an application that was utilizing objects with lazy loaded properties. To make a long story short the lazy loaded properties were causing an extra database hit for every row of data that was being displayed on the screen.
To tie this into a couple of my recent posts on Domain Driven Design let me state that although I'm not sure it would have prevented the problem, I think had I created repositories for the aggregates within my application I would have avoided the problem. Rather then allowing my objects to retrieve data from the database I should have had everything go through a repository. This prevents our objects from running a-muck. Our repositories can control exactly what is and isn't returned, and we reduce the risk of our objects going nuts with database calls.
Beware of the lazy loaded properties!