Search code examples
c++classobjectencapsulation

Encapsulation: Should I pass an object's data to another class which modifies it?


I want to have something like the following piece of code:

class Foo{

public:

    void update() {
        for( auto dataModifier : _dataModifierList ) {
            dataModifier.modify( Data& _data );
        }
    };

private:
    Data _data;
    std::vector<DataModifier> _dataModifierList;

};

Because I am sending Foo's data to another class which modifies it, is this considered poor encapsulation? It feels like I'm exposing the contents of Foo to DataModifier.

The reason I have it this way is because I want to register a number of DataModifiers to each instance of Foo.


Solution

  • If DataModifier gets a reference to Data object to modify it in place, its perfectly fine from the point of view of encapsulation. It would be a flaw if you make DataModifier Foo's friend so it can change its members at any time, without calling any Foo's methods. And if you decide to store the reference to private data_ somewhere outside Foo and than pass it to DataModifier I would also consider it bad design.