在接口中公开方法但在实现中受保护有什么好处?
在我的 C++ 应用程序中,我有一个如下所示的接口:
class ICalculator
{
public:
virtual double calculateValue(double d) = 0;
};
我有该接口的实现,如下所示:
class MySpecificCalculator
{
public:
virtual double calculateValue(double d);
};
现在我的同事对此抱怨并告诉我最好保护calculateValue 方法。这样,我们可以保证调用者始终通过接口传递,而不是通过直接实现。
这是正确的观察吗?保护接口的实现真的更好吗?或者我们甚至不能将其设为私有吗?
In my C++ application I have an interface that looks like this:
class ICalculator
{
public:
virtual double calculateValue(double d) = 0;
};
I have implementations of this interface that look like this:
class MySpecificCalculator
{
public:
virtual double calculateValue(double d);
};
Now my colleague complains about this and tells me it's better to have the calculateValue method protected. That way, we can guarantee that the callers always pass via the interface and not via the direct implementation.
Is this a correct observation? Is it really better to make the implementation of an interface protected? Or can't we even make it private then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的同事是对的。
切勿公开虚拟函数。
Your colleague is right.
Never make virtual functions public.
听起来你同事的意思是:
我看不出这个设计有什么好处。为什么不能从具体参考中调用计算。在派生类中将calculateValue 移至protected 会破坏基类的约定。您不能使用 MySpecificCalculator 来计算 Value,但它的基类是这么说的。
顺便说一句,这种行为并不是按照 Chubsdad 解释的 NVI 惯用法建模的(这是“正确”的方式)。
It sounds that your colleague means:
I cant see any benefit from this design. Why not to be able to call calculate from a concrete reference. To move calculateValue to protected in the derived class, breaks the contract of the base class. You can't use a MySpecificCalculator to calculate a Value, but its base class says so.
Btw this behaviour is not modeled by the NVI idiom explained by Chubsdad (which is the 'correct' way).