Lazy load pattern
An object that doesn't contain all o the data you need but knows how to get it
Contents |
How it works
There are four different lazy load implementations
Lazy initialization
Every access to a field first determines if it's null. If so, it will query the database to retrieving the value (saving the value and then returning it). Works well, but need to ensure that every field access always uses getters and setters (even inside the class), and if null is a valid result there needs to be someway to represent that.
Virtual proxy
An object which looks like the object which should be in that field. When a method is called, that object then retrieves the data from the database. This does mean you need to create a lot of virtual proxies for each different type that needs to be queried.
Value Holder
Similar to the virtual proxy - except that there is only one generic type that can be anything. It will return the actual value which will need to be casted back to the correct type.
Ghost
A real object in a partial state. When it is first created, it only contains its ID. The first time that any field is queried, all the other fields are populated at the same time.
When to use it
It depends on how expensive database calls and memory is. If the class only contains data from a single row, then it isn't a good idea to use lazy loading (as it does not cost extra to bring back the rest of the data in the row). Consider lazy loading if a field requires a complex join operation and isn't frequently used.