I am somehow confused with the concept of composition and encapsulation.
Here is the example which helps my bottleneck : I have a class A, which has parts of types B and C. B has also parts of types D and E.
class A
{
B itsB;
C itsC;
}
class B
{
D itsD;
E itsE;
}
class D
{
int mAlpha;
int getAlpha();
void setAplha(int);
}
A itsA;
For this case, how do you read-only access mAlpha ?
This way ? itsA->getItsB()->getItsD()->getAlpha()
or this way ? itsA->getAlpha()
, where A::getAlpha()
accesses itsB->getItsD()->getAlpha()
What about the way to write access mAlpha ?
This way ? itsA->getItsB()->getItsD()->setAlpha(10.0)
or this way ? itsA->getItsB()->setAlpha(10.0)
, where A::getAlpha()
accesses itsB->getItsD()->setAlpha(10.0)
So the question is ; to access/modify the parts of a composite class, while obeying the encapsulation principle, should you access only via the composite class' interface ?
Otherwise, it seems that you access the part, modify it, without the knowledge/permission of the owner composite.
Please help me to get rid of this confusion
Thanks.
So the question is ; to access/modify the parts of a composite class, while obeying the encapsulation principle, should you access only via the composite class' interface ?
According to the encapsulation principle, the composite's parts should be hidden. Assuming that mAlpha
is logically a property of A
, but implemented in D
, you should add accessor methods in A
that look up/change the mAlpha
member in its D
part. Otherwise, you'd be leaking implementation details of A
(that it is a composite of a D
and some other stuff).