I often hesitate to use friend classes in C++. Since it often does not feel right, or just seems to be an indicator of bad design. Though, in this case I think a friend class might improve the design. Let me explain:
Let us say I have a very simple mesh class:
class Mesh {
friend class Renderer;
public:
using Vertices = std::vector<Vertex>;
Vertices::iterator begin() {
return vertices_.begin();
}
Vertices::iterator end() {
return vertices_.end();
}
void invalidate(){
valid_ = false;
}
private:
Vertices vertices_
bool valid_;
}
The renderer looks something like this:
class Renderer {
public:
void render(Mesh & mesh){
if (!mesh.valid_){
//The mesh has changed, update internal data.. GL buffers etc.
mesh.valid_ = true; // Mesh becomes valid again.
}
//render...
}
}
So, this is of course a very simplified example. My question is, if this is a good design in this case? Clients can only call invalidate()
on meshes. And only the renderer is allowed to "validate" a mesh again. Without a friend class, A public setter would have to be used in the Mesh class. Hence providing a "leaky" interface. Allowing clients to "validate" meshes, which I do not want.
Edit to clarify
A valid mesh in this sense means that its corresponsing data in other subsystems is the same. The renderer has its own mesh data in its own form (a GL buffer). Therefore, only the renderer should be able to validate, since it knows about its own mesh data. Clients can edit meshes, and invalidate them only.