Style Case Studies: Construction Unions - Adding New Types
(Page 6 of 9 )
Are you back? All right, here’s the list I came up with. To add a new type, you have to remember to:
- Add a new enum value;
- Add a new accessor member;
- Update the cleanup function to safely destroy the new type; and
- Add that type to the max calculation to ensure buff is sufficiently large to hold the new type too.
If you missed one or more of those, well, that just illustrates how difficult this code really is to maintain and extend.
Pressing onward, we come to the final function:
void MYUNION::cleanup()
{
switch( currtype ) {
case _LIST: {
LIST& ptype = getlist();
ptype.~LIST();
break;
} // case
case _STRING: {
STRING& ptype = getstring();
ptype.~STRING();
break;
} // case
default: break;
} // switch
currtype=NONE;
}
Let’s reprise that small commenting nit: The // case and // switch comments add nothing; it’s unfortunate that the only comments in the code are useless ones. It is better to have no comments at all than to have comments that are just distractions.
But there’s a larger issue here: Rather than having simply default: break;, it would be good to make an exhaustive list (including the int type) and signal a logic error if the type is unknown—perhaps via an assert or a throw std::logic_error(…); .
Again, type switching is purely evil. A Google search for switch C++ Dewhurst will yield all sorts of interesting references on this topic, including [Dewhurst02]. See those references for more details if you need more ammo to convince colleagues to avoid the type-switching beast.
Guideline: Avoid type switching; prefer type safety.
This chapter is from Exceptional C++ Style, by Herb Sutter (ISBN 0201760428, copyright 2005. All rights reserved. It is reprinted with permission from Addison-Wesley Professional). Check it out at your favorite bookstore today.
Buy this book now. |
Next: Underhanded Names >>
More Code Examples Articles
More By Addison-Wesley/Prentice Hall PTR