jeudi 27 décembre 2018

Easy way to run non const methods on nested objects in Composition /Aggregation pattern in C++

I came to from the C# world and, thanks to the "Properties", I can run a setter method on a nested object without leaking any internals like this:

objectA.objectB.objectC.SetSomething();

So far, I found that the best analog in C++ is to use getters and get nested object by const reference than use setters to set them by value. But this would result in the following code:

auto b = objectA().getObjectB();
auto c = b.getObjectC();
c.SetSomething();
b.setObjectC(c);
objectA.setObjectB(b);

Not only this is 5 lines instead of one, but it involves 2 copies of the nested objects in b.setObjectC(c); and objectA.setObjectB(b);

I can let the getters to return non const reference of nested object (or use public variables) and will be able to write in C++:

objectA.objectB.objectC.SetSomething();

But, instantly I get the ability to set objectB without objectA knowledge like this:

objectA.objectB = new b {};

And this is unacceptable in aggregation pattern where parent object initializes nested object.

Other two approaches I read about:
1. Instead of aggregation use multiple protected inheritance and translate needed methods with "using". However, I also read in "Google C++ Style Guide" to never use protected inheritance..
2. Rewrite all required methods in the parent class manually. But this would require for me to write SetSomething() method in both ObjectB an objectA which, in my opinion, violates "Don't repeat yourself".

What am I missing? How can this be done?

Aucun commentaire:

Enregistrer un commentaire