An example using the Conditional Operator.
void setSelected( bool selected )
{
a = selected? SELECTED_VALUE_A: DEFAULT_VALUE_A;
b = selected? SELECTED_VALUE_B: DEFAULT_VALUE_B;
c = selected? SELECTED_VALUE_C: DEFAULT_VALUE_C;
}
An example using an if and temporaries.
void setSelected( bool selected )
{
a = DEFAULT_VALUE_A;
b = DEFAULT_VALUE_B;
c = DEFAULT_VALUE_C;
if ( selected )
{
a = SELECTED_VALUE_A;
b = SELECTED_VALUE_B;
c = SELECTED_VALUE_C;
}
}
An example using functions
void setLook( int nA, float nB, std::string nC )
{
a = nA;
b = nB;
c = nC;
}
void setSelected( bool selected )
{
if ( selected )
setLook( DEFAULT_VALUE_A, DEFAULT_VALUE_B, DEFAULT_VALUE_C );
else
setLook( SELECTED_VALUE_A, SELECTED_VALUE_B, SELECTED_VALUE_C );
}
An alternate example using functions. Still uses setLook
void setLookSelected()
{
setLook( SELECTED_VALUE_A, SELECTED_VALUE_B, SELECTED_VALUE_C );
}
void setLookNormal()
{
setLook( DEFAULT_VALUE_A, DEFAULT_VALUE_B, DEFAULT_VALUE_C );
}
void setSelectedAF( bool selected )
{
if ( selected )
setLookSelected();
else
setLookNormal();
}
//Or just call
setLookSelected();
setLookNormal();
Let’s simplify the requirement:
Using the conditional operator:
IMHO, as clear as it can get
Using temporaries and if:
Really ugly. You assign
ctoa, even if!b. Besides the awful readability, you encounter performance drop, as you have a double assignment. The optimizer could take care of that, but don’t count on it.Using functions:
This could be useful if you have a lot of members that you want to set. Code maintenability will be improved. You’d only need to change in one place if you want different functionality. Not bad!
Alternate functions:
Another option I’d advise against. What if you don’t want to check only for
bin the future? What if the two variants aren’t exclusive, i.e. you want to combineID_NODE_GLOW_SELECTwithID_NODE_COLOR_NORMALfor some other condition?Conclusion: I’d use the first variant for simple, small cases, and the functions with parameters for large classes, where you set a lot of members. I’d definetely stay away from options 2 & 4.