我将抽象基类定义为 API 的一部分,供其他开发人员使用,有点像定义 Android API 并让开发人员使用它来制作手机应用程序。API 的创建者(即我)何时应该提供某些功能,以及创建者何时应该将其留给开发人员(即 API 的用户)来定义该功能?
这是一个相关的示例:假设我正在定义MyObj的通用树(用户可以在其中创建从MyObj派生的类并具有子类和父类,并且可以通过类型和值进行过滤。
class MyObj
{
public:
// These must be provided
MyObj const * parent();
bool setParent(MyObj const * i_obj);
std::vector<MyObj const * > children() const;
bool addChild(MyObj const * i_obj);
bool removeChild(MyObj const * i_obj);
// The following functions can be implemented
// by using the functions listed above.
// Should I provide them (by leaving them in the class or
// defining them as utility functions, etc), or should I let
// the developers define them?
MyObj const * root() const;
bool hasChild(MyObj const * i_obj) const;
std::vector<MyObj const * > descendants() const;
std::vector<MyObj const * > childrenFiltered(FilterType i_type, FilterValue i_val) const;
std::vector<MyObj const * > descendantsFiltered(FilterType i_type, FilterValue i_val) const;
private:
std::vector<MyObj * > m_children;
MyObj * m_parent;
};
需要考虑的事项:
- 如果它涉及使用私有变量,以至于开发人员(API 的用户)自己无法提供该功能,那么我必须提供它。
- 如果某些功能将被许多开发人员(API 的用户)使用,请自行定义。这样一来,开发人员 A 就不需要开发开发人员 B 开发的相同的一组非常有用的实用功能;他们都会使用我提供的那些。
- 另一方面,也许最好不要试图预测基类将如何使用,而是提供允许开发人员做任何他们想做的事情所需的最少功能。
- 如果功能是核心功能,提供它(即使它可以只使用其他公共功能来实现)
- 确定某事是否是核心功能似乎是一项相当模糊的业务
相关文章: