Share on FacebookThe other day I run into a little problem, which I thought worth of mentioning. It’s really kinda obvious when you think about it, but I didn’t, until I run into it.
First, a little background for those that don’t know what LazyLoading or Serialization are.
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used
So basically, you implement your properties (of complex objects) in such a way that they get instantiated only when the property get is called; something like this

In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be stored on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward.
The “not straightforward” part, is often solved getting the object referenced in the property, and serializing it also.
So, could you spot the problem?
Whenever an object that implements LazyLoading gets serialized, all its properties are called, which breaks the whole LazyLoding concept.
My specific problem appeared because I used an entity both to display a list of objects with a listview, that used the code and description properties, and when you clicked on one it would redirect you to an edit page, where the full object would be loaded so it could be edited.
I “fixed” it with a tiny little flag; since I have a Service class that calls a DataMapper to load the entities, I knew from where I was calling it, so I added a parameter to pass whether LazyLoading should be cancelled; in the above example, additionally to checking if the private field was null, I also checked this flag, and loaded it only if it was false. This greatly reduced rendering times.
I know it’s not a really good fix, so I though of leaving an open question to everyone… how would you solve this?
Other options I thought were:
- Having two different entities, one lightweight for the list, and one for the full edit page. This would double the Service and DataMapper classes, and it was a lot of work.
- Having two different entities and use inheritance to reduce that Data Access layer duplication. It seemed it wouldn’t be that clear, and still it seemed like a lot of work.
- There was another option that I cannot recall right now.
Anyway, it’s an interesting problem, isn’t it?
What would you have done?