I'm wondering if it was considered a bad practice, or something that breaks the rules of OOP, the fact of according an access to a private member to a specific object. To be really clear here is a code example.
我想知道它是否被认为是一种不好的做法,或者某种违反OOP规则的事情,即根据私人成员访问特定对象的事实。要清楚这里是一个代码示例。
// A special class used to perform some operations on a "Restricted" object
class RestrictedExplorer
{
public:
Explorer(SpecificData * data) : m_data(data) {}
private:
SpecificData * m_data;
};
// This class is the only one able to give access to its private member to an explorer
class Restricted
{
public:
Restricted() { /* ... */ }
RestrictedExplorer * getExplorer() { return new RestrictedExplorer(m_data); }
private:
SpecificData * m_data;
OtherData * m_other;
};
We can see that the class itself allow a specific object to use its private data, and it only gives a part of its private member. Plus, it's impossible for another RestrictedExplorer to have access to the private member of a Restricted object by itself.
我们可以看到类本身允许特定对象使用其私有数据,并且它只提供其私有成员的一部分。另外,另一个RestrictedExplorer不可能自己访问Restricted对象的私有成员。
As long as the RestrictedExplorer respect the encapsulation, is this design something to avoid because it breaks the OOP, or is it possible to use it ?
只要RestrictedExplorer尊重封装,这个设计是否需要避免,因为它会破坏OOP,或者是否可以使用它?
Thanks by advance
谢谢你提前
PS : It's for a school project, we are not allowed to use friend
PS:这是一个学校项目,我们不允许使用朋友
1 个解决方案
#1
0
Without a specific context (use-case), there isn't a correct form. The above getter/setting of a private member is fine as long as the class does not make assumptions as to the internals of m_data as you are allowing others to control its contents. If it does then it should not provide a mutable interface to it.
没有特定的上下文(用例),就没有正确的形式。只要类不对m_data的内部进行假设,上面的私有成员的getter /设置就可以了,因为你允许其他人控制它的内容。如果它确实那么它不应该为它提供可变的接口。
Some (likely most) would consider the above a good practice for any member variable that should be public as you can at lease observe access to the variable through the getter. If it were a public member variable you would not be able to do so.
一些(可能是大多数)会认为上述是应该公开的任何成员变量的良好实践,因为您可以通过getter观察对变量的访问。如果它是公共成员变量,您将无法这样做。
#1
0
Without a specific context (use-case), there isn't a correct form. The above getter/setting of a private member is fine as long as the class does not make assumptions as to the internals of m_data as you are allowing others to control its contents. If it does then it should not provide a mutable interface to it.
没有特定的上下文(用例),就没有正确的形式。只要类不对m_data的内部进行假设,上面的私有成员的getter /设置就可以了,因为你允许其他人控制它的内容。如果它确实那么它不应该为它提供可变的接口。
Some (likely most) would consider the above a good practice for any member variable that should be public as you can at lease observe access to the variable through the getter. If it were a public member variable you would not be able to do so.
一些(可能是大多数)会认为上述是应该公开的任何成员变量的良好实践,因为您可以通过getter观察对变量的访问。如果它是公共成员变量,您将无法这样做。