Hi, I’ve got a philosophical question about the set and get methods of classes. I will try to make it clear…
Let say we have typical user class called « classC » with set and get methods, like:
1 2 3 4 5 6 7 8 9
|
Class C
{
…
int value
…
void setValue (const int intValue);
int getValue();
…
}
|
Then we’ve got a classB that have a vector of classC (composition, not inheritance) :
1 2 3 4 5 6 7 8
|
Class B
{
…
vector<classC> vectorC;
…
const vector<classC> & getVectorC() const;
…
}
|
And a class classA wich one composed of classB :
1 2 3 4 5 6 7 8
|
Class A
{
…
vector<classB> vectorB;
…
const vector<classB> & getVectorB() const;
…
}
|
This could go on and on…
I put the return value of the get methods as a reference cause I don’t want to have a copy of the vector for memory and performance consideration. I set the returned reference constant to ensure no direct modification of value in vectors…
What is the best practice to modify the value variable of a classC object contains in the vectors of classA? I see two ways, but cannot define which on is the best :
1. Create a temporary classC object, assign it a copy of the classC object to modify, modify the value with the set method, delete the original class object in the vector and push the new one. Which is a couple of operation, like :
1 2 3 4 5 6 7 8 9 10
|
classC tempC;
std ::vector<classC> ::iterator fwdIterator;
// use a loop or other mean to set the iterator to the correct classC object
…
// the classes contain the assignment operator overload…
tempC = *fwdIterator;
tempC.setValue(z);
classAObj.getVectorB().at(x).getVectorC().erase(fwdIterator);
classAObj.getVectorB().at(x).getVectorC().push_back(tempC);
|
2. Create a setValue method in classA and classB to allow direct modification of classC value :
in classB :
1 2 3 4
|
void setClassCValue(const int position, const int newValue)
{
vectorC.at(position).setValue(newValue);
}
|
and then in classA :
1 2 3 4
|
void setClassCValue(const int bPos, const int cPos, const int newValue)
{
vectorB.at(bPos).setClassCValue(cPos, newValue);
}
|
If there is a lot of data manipulation, the second choice seems more interesting because a simple call to classA set method is required. But as there are more and more variables in class B and C, and more composition, the number of set methods to define will increase rapidly…
So, what would be the « best pratice » ?
Regards,
Éric