I'm creating an API where MANY objects share MANY functionalities.
My primal instinct is to use inheritance however they do not strictly adhere to "is-a" type relationship - it's only the "functionalities" that are shared. For example, it is not engine->turbo_engine, engine->combustion_engine type relationship. Loosely speaking, it's more so brand->car, brand->plane. Inheritance is convenient because brand obj has useful functionality such as company name, etc. that are useful in many classes. Inheritance makes it easy to expose functions of the brand class.
However, I'm afraid to use inheritance as it would make everything strongly coupled. Likely leading to fragile base class issues in the future.
My concern with composition is having to manually write MANY wrapper functions to expose public methods of the brand class in the above example (is that a valid concern?). To make it easy to expose functionality, I used std::function and std::bind.
Below is a dummy code showing my approaches.
With inheritance:
It feels wrong to use inheritance without a strong "is-a" relationship. With this approach, I would have to do multiple inheritances. Overall, leads to strong coupling? (which I perceive to be bad?).
Class Identity //Stores name, id and has functions such as Get/SetName, Get/SetId, etc.
Class TypeA : Public Identity
Class TypeB: Public Identity
...
My solution with composition (to avoid copying code/writing wrapper functions):
Class Identity
{
int GetId(){}
}
Class TyepA
{
Identity identity_;
std::function<int(void)> GetId;
TypeA():
GetId(std::bind(&Identity::GetId, &identity_))
{
}
}
Can you please share your thoughts on this? I'm inexperienced with large software designs so I'm struggling to start off on the right path.
Aucun commentaire:
Enregistrer un commentaire