I was browsing my teacher’s code when I stumbled across this:
Order* order1 = NULL;
then
order1 = order(customer1, product2);
which calls
Order* order(Customer* customer, Product* product)
{
return new Order(customer, product);
}
This looks like silly code. I’m not sure why, but the teacher initialized all pointers to NULL instead of declaring them right away(looking at the code it’s entirely possible, but he chose not to).
My question is: is this good or acceptable code? Does the function call have any benefits over calling a constructor explicitely? And how does new work in this case? Can I imagine the code now as kind of like:
order1 = new Order(customer, product);
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:
just before
order1is required.If there is any reason to separate the declaration of
order1from the instantiation, like this:order1should 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
Ordermay 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.
Ordermay come from a 3rd party library and can’t be changed, or instantiation needs to add validation that isn’t within the scope ofOrder:(2) You may need an order that behaves differently.
However, I wouldn’t make this a general pattern blindly.