A class A possesses an instance c of a class C. Another class B has to modify c through C::setBlah(); method.
Is it bad to create an accessor C getC(); in A and then use A.getC().setBlah() ?
Or should I create a method A::setBlah(); that would call C::setBlah(); ? Isn’t it annoying if there are several methods like that ?
As with most “is it bad to do X?” questions, the answer is that it depends entirely on a given situation.
Sometimes it might be a really bad idea to have a
getC()sort of function because it breaks encapsulation. Other times it might be completely fine because encapsulation of that detail might be irrelevant, and writing a lot of wrapper functions increases the amount of code that you have to write.Pick whichever makes the most sense for the given situation. In code that I’ve written, I’ve taken both approaches.
If you do go the
getC()route, do make sure you return a reference; otherwise you’ll be modifying a copy which doesn’t sound like what you want. Or, you might consider makingA::cpublic so that you don’t need a function at all.A third option to consider would be inheritance from
C, which removes the need forgetC()or wrapper functions inA.