Optional Member Objects
- by David Relihan
Okay, so you have a load of methods sprinkled around your systems main class. So you do the right thing and refactor by creating a new class and perform move method(s) into a new class. The new class has a single responsibility and all is right with the world again:
class Feature
{
public:
Feature(){};
void doSomething();
void doSomething1();
void doSomething2();
};
So now your original class has a member variable of type object:
Feature _feature;
Which you will call in the main class. Now if you do this many times, you will have many member-objects in your main class.
Now these features may or not be required based on configuration so in a way it's costly having all these objects that may or not be needed.
Can anyone suggest a way of improving this?
At the moment I plan to test in the newly created class if the feature is enabled - so the when a call is made to method I will return if it is not enabled.
I could have a pointer to the object and then only call new if feature is enabled - but this means I will have to test before I call a method on it which would be potentially dangerous and not very readable.
Would having an auto_ptr to the object improve things:
auto_ptr<Feature> feature;
Or am I still paying the cost of object invokation even though the object may\or may not be required.
BTW - I don't think this is premeature optimisation - I just want to consider the possibilites.