Lazy Initialization
One of the most critics about Object Orientation for real world projects I get during the speaks is: OOP isn't performant. Considering a very simple example where a class Customer contains a list of classes Order. For the best OO philosophy we should have three types: Customer representing a single customer entity, Order which is an order entity and an Orders class wich is a list of Order entities (strongly typed collection of Order types).
Normally, all objects are, in some way, mapped over a relational database and when the consumer wants some information about a customer, they are loaded from the database.
The standard .NET way (many devs adopt this one) is to use a DataSet with two DataTable with a relation. The OOP way should be to load all informations from the database (maybe using a ORM tool) and expose them through it's object model.
This approach can provide some performances drawback when we load all informations (for all entities) at the same time (object creation time), especially if we need only some info from the customer and not it's orders.
Another approach consits in loading the deep information (in this sample the Orders) only on demand, as the Lazy Initialization pattern suggests.
Considering the following pseudocode:
public class Customer {
// all code here
public Orders CustomerOrders;
public void Load(int customerID) {
// Load the customer from DB and also it's orders (ie. Orders.Load(customerID))
}
}
Can be refactored to:
public class Customer {
// all code here
private Orders _customerOrders = null;
public Orders CustomerOrders {
get
{
if(_customerOrders == null)
_customerOrders = Orders.Load(customerID);
return _customerOrders;
}
}
public void Load(int customerID) {
// Load only the customer from DB
}
}
As we can see the orders are loaded from the database only if really needed. This pattern is applicable to all objects where the creation of some instance variables cost either in terms of time or memory and they may never be used. This pattern is used as basis of a large numer of aother patterns, such as Singleton.
The sample above isn't thread safe but I will talk about it another time. Stay tuned :-)