Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Typedefs and Iterators: If you've Got 'Em, Use 'Em


September, 2004: Typedefs and Iterators: If You've Got 'Em, Use 'Em

Typedefs do more than just reduce clutter and save keystrokes; they can help smooth the transition when requirements change. Iterators are an even more powerful tool for implementation hiding and reducing coupling due to container choices. But both techniques can only help if you actually use them!

Herb Sutter (http://www.gotw.ca/) is a leading authority and trainer on C++ software development. He chairs the ISO C++ Standards committee and is a Visual C++ architect for Microsoft, where he is responsible for leading the design of C++ language extensions for .NET programming. His two most recent books are Exceptional C++ Style and C++ Coding Standards (forthcoming October 2004).

Jim Hyslop is a senior software designer for Leitch Technology International. He can be reached at jhyslop@ ieee.org.


Iwas in the zone, pounding out code at a steady rhythm. "Why are you doing that?" Wendy's voice floated over the cubicle wall. As usual, there was no context, so I had to ask for clarification.

"Huh?"

"You aren't taking proper advantage of the typedefs available to you." She came around to my cubicle, shooed me out of the way, and sat down at my keyboard. After a few swift keystrokes, she called up a class I had recently worked on:

class SomeClass {
public:
  typedef std::list<int> Items;
  void DoSomething( const Items & );
  // ... etc. ...
};

"Riiight," I drawled, "so what's wrong with that?"

"Nothing, yet. You've declared a typedef for your list to make it easier for yourself, right?"

"Well, yeah, so there's less typing."

"OK, now watch this," she hit a few more keys, and called up this source code:

list<int> theItems;
// ... fill in theItems ...
SomeClass s;
s.DoSomething( theItems );

"Here's the problem, pardner. Our original analysis showed that a list was the best container to use, right?" I nodded, and Wendy continued. "Well, the requirements have changed, and we need random-access iterators. So now the best container to use is a vector. I changed the typedef, but because you've explicitly declared a list in the calling code—and not just here, in a lot of places—a lot of code now breaks."

"But wait a second," I said. "When I wrote that part of the calling code, the typedef wasn't around yet. I added it after already writing list in a few places."

A loud snap interrupted me as the Guru arrived, loudly shutting her tome of the day. "If we ignore coupling issues for a moment," the Guru said, "that is all the more reason to add the typedef immediately. Consider the reason the keyword typedef exists. It is not merely a convenience, to shorten your typing. Indeed, SomeClass::Items requires more key presses than list<int>. No, my child, the typedef exists to imbue your writings with lower coupling, at least lexically, by introducing a lexical abstraction: a name."

While the Guru was still speaking, Bob was passing by, overheard, and changed course in our direction. This was getting to be quite the little party. "Kid, you gotta learn when not to listen to Her Weirdness and her fancy-pansty talk," Bob said as he approached. "Kerry told me you were talking about this, so I figured I'd add my bit of expertise to the discussion."

I heard a strange noise beside me, and realized Wendy was growling. I hooked my fingers under her belt—just to be safe.

Bob ignored her as he continued. "See, I like to know what I'm dealing with. S'pose we take your code, and change it to use the typedef." He picked up the marker and started writing on the whiteboard:

SomeClass::Items theItems;
theItems.what???

"At this point, I'm stuck. I don't know what I can do with an Items object. On the other hand, list<int> I know how to deal with." And he wrote:

list<int> theItems;
theItems.push_back( 42 );

"I don't buy it," I interrupted him, and picked up a different marker. "Say you come across a class that's new to you, like this..." I wrote on the whiteboard:

AStrangeClass widget;
widget.Frobnosticate();

"Then if you have to modify the code to do something else, you don't just stare at AStrangeClass hoping for inspiration to tell you what to do, right?" I paused. "Right?"

Bob mumbled something.

"Well, I would look up the documentation of AStrangeClass to see what operations can be performed on it. So why wouldn't people just look up the documentation of SomeClass::Items and see that they are using a list? The documentation may be as simple as finding the typedef."

"Now that I think about it some more, I'm not sure I agree with either of you," Wendy said. "Both of you are still making things very container dependent, so that calling code has to use a particular container. 'Course, the whole point is that in the status meeting this morning we decided to change the function parameter type from list to vector. What if we had to change it to something that doesn't support push_back, like maybe a map or a set?"

I tried to wave it off. "Look, if you have to change the type, you're gonna break a lot of code no matter whether you use the typedef name, or the original type." Seeing the glazed look in Bob's eyes, I hastened to add: "SomeClass::Items or list<int>."

"On the other hand," Wendy chimed in, "if you use the typedef name, then you can easily grep the source code for all occurrences of that typedef, to examine the exact impact of your changes. And you won't get any false hits—searching for list<int> could turn up a lot of hits that have nothing to do with this class."

"Bah, my latte's cold," Bob muttered, and stomped off. The atmosphere immediately lightened perceptibly.

"But there's a fundamental unanswered question," I mused aloud to Wendy and the Guru. "What if you do want to insulate people from having to rewrite their code at all if you need to make a function signature change like we did when we changed from list to vector, which could just as well have been to something like set? I know, I know," I waved, "'beware the illusion of container-independent code...'"

The Guru smiled. "Indeed. Third Meyers, chapter two, verse 1." [1]

"...But still," I pressed on, "why should you care if calling code uses a list or whatever? Why should the container that calling code uses matter in this case?"

"Indeed," the Guru smiled again. "And the canonical answer, my child?"

"Iterators," Wendy put in before I could respond, and she wrote on the whiteboard:

class SomeClass {
public:
  template<typename IntIter>
  void DoSomething( IntIter first, 
                   IntIter last );
  // _ etc. _
};

"The code inside DoSomething is pretty much unchanged," Wendy explained. "The code assumes that first and last are iterators that, when dereferenced, yield ints. It shouldn't care what container the caller's using. That's way better decoupling, see?" And she demonstrated:

vector<int> theItems;
// ... fill in theItems ....
SomeClass s;
s.DoSomething( theItems.begin(), 
              theItems.end() );
set<int> moreItems;
// ... fill in moreItems ...
s.DoSomething( moreItems.begin(), 
              moreItems.end() );

"Ah," I ahhed, "and, well, y'know, I think it gets even better because in fact the contained elements don't even have to be exactly ints either, as long as they're convertible to ints." I added:

set< char > yetMoreItems;
// ... fill in yetMoreItems ...
s.DoSomething( yetMoreItems.begin(), 
              yetMoreItems.end() );

"Much better," the Guru agreed. "Typedefs are very useful for lexical insulation, and iterators are the insulation that enable the only fully container-independent code. In short, my children," she said as she glided away, "If you got 'em, use 'em..."

References

  1. [1] Scott Meyers. Effective STL, Addison-Wesley, 2001.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.