In short
Fundamentally, there is no universal right or wrong to this question. It all depends on the responsibilities that you want to give to your classes in their collaborations. But in the majority of the cases, don't !
Pros - When to do this ?
If it's the sole responsibility if the Person
to change the color, and nobody else should care about the House
, then your design makes sense. It has the the advantages of hiding the delegation as already nicely explained by SDJ.
But this is not the sole way to distribute the responsibilities between the classes, and there are many reasons to leave the design more open, for example:
What if the Person
doesn't paint her house herself, but asks a Painer
to do the job on her behalf? What if, hypothetically, the mayor of the village would have the power to decide on the change of color, and send his painters accross the village ?
Cons - avoid it if possible !
There is a big disadvantage in your design. It has to do with the Single Responsibility Principle (SRP):
A class should have only one reason to change
Adding changeHouseColor
implies that Person
has more than one reason to change: first it may change with the concept of Person itself. But it might then also have to change as consequences of changes in House
. For example, if tomorrow, the interface of House
evolves to require an additional thickness parameter for changeColor
, not only would your Person
implementation change (providing the additional parameter in the delegation call), but also the Person
interface would have to change, so that the thickness is provided as well. So a small change in House
would propagate to all the class using Person
. The hidden coupling can quickly become a technical debt.
If you start to replicate every method in every class that could remotely access it, you will further face a combinatorial explison in your interfaces, which would quickly freeze the evolution of any interface because of the risk of change propagation.
Conclusion
Separation of concerns should drive your design. If the concept of Person
is independent of the concept of House
, do not couple them unnecessarily. Do this only if there is a strong need to do so (for example if the house is private and nobody has to know anything about it).
Also, in UML there is no need to add changeHouseColor()
method to show that a person can change the colour of the house. The simple association between Person
and House
shows that Person can invoke any public method of House
.
If you provide a getHouse()
in Person, or if you'd add a public +myHouse
at the house end of the association, you would also communicate that other classes can access a Person
's House