Class design suggestions: extending a class and code reuse

让人想犯罪 __ 提交于 2019-12-05 06:58:10

Especially if the methods are specific to your departments use of the class you should implement them as in: Create a single Helper class, with all the methods inside.

There are several reasons for this:

  • The single helper class can be located in another logical project structure
  • If your new methods don't require access to the internal state of the class this is expressed clearly. It provides better encapsulation. (which you supplemented by const ref, which is think is a good style)
  • UsedByManyPeople shouldn't be responsible for converting itself into another type. This violates SOLID

the last option won't affect anyone else, and isolates your one-off needs into a single class

You shouldn't change the existing UsedByManyPeople class. If your department has preferences on what patterns to use, then stay within your department's style. Otherwise, create the helper class for conversions. If you see multiple conversions down the road you may want to create a class for each conversion. For the getFileName extension, you might want to derive a class (if this is in fact a useful extension) or add it to your helper.

Again, your department's standard (if one exists) should guide you on this. If you don't have a standard, now's the time to create one.

Although this is almost identical (in usage at least) to the class with public static methods, you could use a namespace to encapsulate the routines you need (as said before, this will only work provided the calls can be implemented from the public data and methods of the original class).

namespace MyDept
{
    SomeOtherType const convert( UsedByManyPeople const& );
    std::string   const getFileName( UsedByManyPeople const& );
}

which provides a very similar interface to the caller as the static calls from a class, for instance

overusedObjectAsSomeOtherType = MyDept::convert( overusedObject );

I'd like to hear from the other people that have answered on this list as to whether there are any real differences between this approach and the one that was overwhelmingly selected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!