I have a class that contains some members that may be modified from external sources:
class CNode
{
protected:
// these members might be changed by users
std::string m_sName;
CState m_CurrentState;
CColor m_DiffuseColor;
};
The sample is simplified, it has more members in my code.
Now what would be the best practice to change
- single
- multiple (at once)
- all members (at once)
of this class?
My code needs to handle all cases, though internally case 1. will be the usual case. Most of the time it is applied to a single CNode but it might also be applied to an array of nodes.
I know two possible solutions that both don't really satisfy me:
- set&get for every variable:
Pro:
Every variable is modifiable independently from other members.
Easy to set the same value for multiple CNodes.
Contra:
A lot of set&gets;
If a new variable is added, a new set&get needs to be added as well.
This would work best if one Variable is changed in many CNodes
- Create a CProperties class that contains all modifiable variables:
Pro:
One set&get in the parent class - properties may be added/removed without needing to modify set&get.
This also reduces the amount of methods in my API that processes user input.
Contra:
setting individual variables requires getting the current CProperties, so the other values won't be modified.
This would work best if multiple/all variables are updated at once in a single CNode.
Like so:
class CProperties
{
// these members might be changed by users
std::string m_sName;
CState m_CurrentState;
CColor m_DiffuseColor;
}
class CNode
{
public:
const CProperties* GetProperties();
void SetProperties(CProperties*);
protected:
CProperties m_Properties;
}
This would be the most lazy version (by code creation effort) but also the most obnoxious version for me, since setting single variables requires getting the current properties first, modifying a single variable and then setting the complete properties class back to the node.
Especially in the modify-a-single-variable-in-multiple-CNodes-case this seems to be an awful solution.
Time of execution and (size) overhead is mostly irrelevant in my case. (Which would really be my only good argument against the lazy version)
Instead I'm looking for clean, understandable, usable code.
I could think of a third possible solution with a dynamic approach:
One set method has an object as parameter that may contain one or more values that need to be modified. The API then only has one set method that won't need any modification if the CProperties change. Instead a parsing method would be needed in the CNode class.
This parsing method would still need to be updated for every change in the CProperties, though I'm confident this should also be solvable with the compiler through templates.
My question is:
Are there any other possible solutions for my use case?
Which approach is the most sensible one?