Reputation: 35
I am fairly new to C++ and I am still learning to write clean code.
Below are excerpts from the current legacy code I have.
class A {
public:
setDataManager(dm)
{
_dm = dm;
}
void recieveData(data)
{
_dm.processData(data);
}
private:
std::shared_ptr<DataManager> _dm;
};
class DataManager {
public:
void processData(data)
{
DecodeData dd;
dd.Decode(data);
if (decoded data conatains a value XYZ) {
doActionA();
}
}
};
class DecodeData {
public:
void decode(data)
{
//if data contains key 1
// store the value (setters and getters defined)
//if data contains key 2
// store the value.
......
}
};
main()
{
//ConfigManager reads the location type from config file
A a;
std::shared_ptr<DataManager> dm = std::make_shared<DataManager>(...);
a.setDataManager(dm);
//a.recieveData() gets called
}
The Data received is specific for the type of location.
Currently, the legacy code is defined only for one location(NewYork).
Now I have to add another location to the configuration Manager(Australia).
That means I need to add more statements to decode(data) and additional doActions()
in processData()
;
I want to write clean code by separating out the processing for location NY and Australia, as the data received is different for different locations. I want to have base class, and split out the processing based on location types.
I am unable to conceptualize it. Is it possible? How do I approach it?
Thank you.
Upvotes: 0
Views: 116
Reputation: 11400
You can create a shared pointer to a derived class and assign it to a shared pointer to a base class. That seems to be the only piece you are missing.
#include <memory>
class Base
{
public:
virtual int Foo();
};
class Derived:public Base
{
public:
virtual int Foo();
};
int main()
{
std::shared_ptr<Base> ptrBase = std::make_shared<Derived>();
ptrBase->Foo();
}
So, in your case, you just need to create the right type of DataManager
with something like
std::make_shared<DataManagerSpecial>;
and pass it in. Then, be sure the DataManager
has the correct and flexible API in its base class. DataManagerSpecial
obviously needs to derive from DataManager
.
Upvotes: 2