The essence of this question is to expand the class, minimizing jam packaging in just one class and maximizing code reuse. After reading this question, please feel free to edit the title or description to make it more concise. Although the post looks long, I just try to be solid using a lot of examples.
Suppose I have a class:
class UsedByManyPeople {
As the name suggests, this class is used by many developers. I need to add 2 classes to this class:
- a convert () that converts UsedByManyPeople to SomeOtherType
- getFileName (), which returns a string
Both are specific to my department needs.
First try solution
At first, I thought of simply adding 2 new methods to UsedByManyPeople. Thus, the class will look like this:
class UsedByManyPeople {
However, the two functions are actually specific to my use case for my department, while the other departments do not even have a SomeOtherType class definition and do not care about getFileName ().
Clearly, the above approach is not a good approach (?).
How would you extend this class?
Alternatives that came to my mind:
Subclass UsedByManyPeople and create my own class.
- Link data and method together
For example,
class ExtUsedByManyPeople : public UsedByManyPeople { public: SomeOtherType const convert() const; std::string const getFileName() const; };
Create helper classes, one for each method (yikes!) And implement it as static methods.
- Separate data from methods, responsibility of one class.
For example,
class UsedByManyPeopleToSomeOtherTypeConverter { public: static SomeOtherType const convert(UsedByManyPeople const&); }; class UsedByManyPeopleFileName { public: static std::string const getFileName(UsedByManyPeople const&); };
Create one Helper class with all the methods inside.
- Separate data from methods, one class many responsibilities
For example,
class UsedByManyPeopleHelper { public: static SomeOtherType const convert(UsedByManyPeople const&); static std::string const getFileName(UsedByManyPeople const&); };
c ++ oop class-design
sivabudh
source share