Init to NULL
[edit] since there's a valid discussion, I've changed the order of the options a bit to emphasize the recommended option.
Variables should be declared as local and as late as possible, and initialized immediately. Thus, the most common pattern is:
Order * order1 = order(...);
just before order1
is required.
If there is any reason to separate the declaration of order1
from the instantiation, like this:
Order * order1; // Oh no! not initialized!
// ... some code
order1 = order(...);
order1
should be initialized to NULL, to prevent common bugs that occur with uninitialized variables, easily introduced when // some code changes
.
Factory method
Again, there's some more change resilence here: the requirements for instantiating an Order
may change. There are two scenarios I can think of right off top of my head:
(1) Validation that can't be done by Order's constructor. Order
may come from a 3rd party library and can't be changed, or instantiation needs to add validation that isn't within the scope of Order
:
Order* order(Customer* customer, Product* product)
{
// Order can't validate these, since it doesn't "know" the database
database.ValidateCustomer(customer); // throws on error
database.ValidateProduct(product); // throws on error
return new Order(customer, product);
}
(2) You may need an order that behaves differently.
class DemoOrder : public Order { ... }
Order* order(Customer* customer, Product* product)
{
if (demoMode)
return new DemoOrder(customer, product); // doesn't write to web service
else
return new Order(customer, product);
}
However, I wouldn't make this a general pattern blindly.