Tuple Madness and STL in C++ 52

Posted by tottinger Fri, 20 Jul 2007 03:21:00 GMT

I have already complained about Tuple Madness with reference to Python and Ruby, and UncleBob has seen the same problem and noted it on the old blog. I have come to realize that the same problems appear in modern C++ code.

I have always looked at the STL as a way of implementing a class, but never as a replacement for “real” classes with named member values. In some ways, I think that templates have made our C++ code worse.

For instance, I need a two-member structure. Say I am going to store Name and Address. Now, those with C background would immediately think along these lines:
    struct name_and_address { char name[34]; struct address address; };
    struct name_and_address get_name_and_address(void);
    // blah blah blah

    struct name_and_address x = get_name_and_address();
    printf("%s", x.name );
    printf("%s", x.address.line1);
    // ... and so on...
    printf("%05d", x.address.zip);

Got to love those old C programmers. There is a nice, primitive struct, maybe with a nice, primitive struct embedded in it. Look at the clear names of those variables. It is even pretty efficient to copy these things. With a Plain Old Data Object, the compiler knows what you’re doing and can do block copies instead of memberwise copies. That can be very efficient, enough that you can often pass structures around by value instead of by reference. That’s kinda cool. That same efficiency also applies to plain old data classes in C++, but a lot of people don’t know it.

Sadly, a modern C++ developer does what? Yeah, he returns a pair. This is annoying because when I call my function, I have to know that the name is now called “first” and the address is called “second”. But that is only for this pair-returning function. In another pair-returning function, “first” means birthday and “second” is account number. Of course the prototype is not always in view, so I have to have more tiles in my window to check my work as I code.

Pair is named well enough for an arbitrary pair of primitive values, but frankly it makes no sense for x,y coordinates or names and address, or for the rolls of two twenty-sided dice. Wait. For the dice, it works just fine. After all, what would you call them? Dice1 and Dice2? But I digress. The point is that for most two-member structures, a two-member structure with named members is probably a better choice.

Now pair is not alone (oh look, a pun). Even when we are dealing with collections, the interface to a vector, map, or set is unlikely to be the right set of names and semantics for our problem domain objects. Maybe our property should be listed, and not push_back()-ed. Maybe we care about a policy, that:
        policy.covers(theCar)
Maybe we’re not so interested in whether list x will:
        x.find(z.first) != x.end()

The fascination with exposing STL containers (combined with unfortunate naming, as given here for effect) is hurting readability. It also is a very unfortunate form of primitive obsession and a violation of the Dependency Inversion Principle.

The people who work on your code with you should not have to reverse engineer your work in order to add new features or correct bugs. The code should be written so clearly that mistaken assumptions will be more obvious. They should not have to chase down typedefs and keep notes on paper to keep track of your structures. They should especially not have to look for data in obliquely named pairs of pairs (x.second.first means “price”? Or was that x.first.second? Or…).

If you write your code with a pair programming partner, you should get plenty of feedback about the readability of your code. Even if you do not work in pairs, you should read your tests when you get back from lunch or a meeting, and you should see if primitive containers, primitive member functions, and template syntax are obscuring their purpose. If your tests don’t speak clearly, then none of the other users of your class can speak clearly. Get the syntax out of their way by giving them reasonable wrapper functions.

You might think that wrapping your containers will cost you performance by adding dispatch here and there, but you might be surprised to find out that not wrapping it may cost you far more by concealing bugs and obscuring functionality than it ever save you in performance. A better policy is to keep your code obvious and simple, and try a little profiling and optimization where it really matters.

Of course, if one was worried about the cost of one dispatch for a named method v. an exposed container, there is always the option to build an inline member function in the header.

I’m mindful that this is not the time for me to rant about C++ programmers who never profile, and who manage performance by rule of thumb and old wives’ tales. There are more of them than us, my dear reader, and I fear their wrath. Maybe some day later, when I’m feeling brave.

My roots run pretty deep into C++, and I appreciate how hard it is to produce a system. I just want the guys who are now running with the ball right now to realize that it is far more valuable to be clear and obvious than they appreciate, and it is far less expensive to do so than they fear.

I guess the points are:

  • Don’t be afraid to write small classes and structs.
  • Don’t be afraid to wrap your containers.
  • Don’t be afraid to use abstraction.
  • Everything does not have to be written in templates.
  • Be afraid to write test code that doesn’t tell a story.
  • Be afraid to give too much access to your data by exposing containers.

Adjust your values accordingly.

Comments

Leave a response

  1. Avatar
    Brian Harleton about 8 hours later:

    Tuple Madness is probably the biggest reason I haven’t jumped onto the Ruby bandwagon yet.

    Much of the Ruby code that I’ve come across (mostly through contracted projects that I later have to maintain) is riddled with very non-expressive code.

    While this is annoying in statically typed languages, the language, being statically type, still gives me information about the object.

    Although recently, this contracting company was ‘forced’ to write some Java code for us and got around the whole statically typed thing by simply using vectors, hashtables and lists for all of their objects. Ugh.

  2. Avatar
    Jonathan Wakely about 10 hours later:

    > Sadly, a modern C++ developer does what? Yeah, he returns a pair.

    Some programmers have always found ways to churn out poorly named, leaky abstractions, even without templates.

    On the other hand, exposing an STL-like interface (even if only begin & end) can be useful for container-like types, because it is a lingua franca and follows the really powerful part of the STL, the concepts behind the generic components.

    With language support for concepts coming in the next C++ standard you’ll be able to provide a (compile-time) mapping for struct {string name; Address address;} so that it can be used in a template expecting a pair<string,Address> with members first and second. That will allow you to use generic templates without having to conform to specific names, so there’ll be even less excuse for tuple madness.

  3. Avatar
    Nevin ":-)" Liber 4 days later:

    The thing is, there are advantages to std::pair (and tr1::tuple) over structs/classes; namely, the comparison operators are already defined for it (making it easy to store as keys in an ordered container, for example).

    boost::tuple also has a streaming operator already defined for it. Along those lines, a particular environment may have other extended functionality (via free functions) already defined for these generic types. It isn’t hard to make a pair or a tuple generically serializable, for instance.

    So we get readable names at the cost of more user code to maintain. Is that worth it? It isn’t always a clear cut ‘yes’, at least to me.

  4. Avatar
    Franck-0 5 months later:

    it’s funny cuz I had also that debate with my coworkers today. They gathered with my boss to oppose me because i was using pair instead of struct. sayin it is less clear blah blah one even said that he thought of second as time (seconds)

    I don’t undestand you people why polluting your code with uncountable structs for the sake of readability… I mean you can put some comments to explain what actually first and second mean. is it so hard typedef string Name; typedef string FirstName; std::pair std::pair

    ...

  5. Avatar
    Tim 6 months later:

    I thought it was pretty clear that the issue is that primitive obsession, especially paired with poor naming, means that the next developer to come along has to reverse-engineer your code to find out what it is returning.

    The whole point of having function names and variable names is we should not have to reverse-engineer functions to find out what they’re returning and why. It should be obvious.

    The pair bit is bad enough, but it’s not as bad as the tuple madness I’ve seen in python and ruby. When you get a list of n-tuples (where the extent n is only apparent in the code you’re calling), you end up having to reverse-engineer a lot of code before you have any idea what you’re working with—or why these transformations are taking place.

    Clearly “x1” or “x.first” is far less obvious than “address.city”. That other programmers can look it up in a comment is not enough. That other programmers can study the function to learn what you put in the pair is not enough.

    The goal here is to keep code devilishly simple. Sometimes that means having more classes and shorter functions, and better names. Hence, I am with your coworkers on this. Clear is a kind of “good” that matters.

    Typedef is better than using unadorned primitives, but quite often a structure or class is better yet.

  6. Avatar
    codechasm.blogspot.com about 1 year later:

    The arguments that you lose built-in behavior when making a custom struct has some merit. Why not use inheritance and getters:

    struct NameAndAddress :: pair<string, Address>  {
        string& name() { return first; }
        Address& address() { return second; }
    };
    

    The correct answer is for the language to have some compile-time reflection capability so that you can “mix-in” the functionality you don’t want to rewrite, such as outputting to a stream, lexicographic comparison, etc.

    I agree completely with this article; although it is unpleasant to write boiler-plate code, it is more clear.

  7. Avatar
    James about 1 year later:

    The advantage of tuples if obviously the ability to create generic code, and for meta-programming… despite some hangups (e.g. index names) the resulting decrease in code size will actually increase readability.

    It is also quite common to use enums to name the indexes into the tuple, giving the best of both worlds.

    E.g.

    tuple row; enum { column, data }; row[data] = “blah”;

    etc.

  8. Avatar
    James about 1 year later:

    The advantage of tuples if obviously the ability to create generic code, and for meta-programming… despite some hangups (e.g. index names) the resulting decrease in code size will actually increase readability.

    It is also quite common to use enums to name the indexes into the tuple, giving the best of both worlds.

    E.g.

    tuple row; enum { column, data }; row[data] = “blah”;

    etc.

  9. Avatar
    DVD to HTC over 3 years later:

    thanks,the post is really good PDF to BMP Converter will give you the satisfied

    output quality and conversion speed. Whether you are professional or novice, you can apply it without any errors. You can even set

    the personalized output effect dgfd

  10. Avatar
    rdb over 3 years later:

    How about something like: void get_name_and_address (std::string &name, address &addr); No need for structs or pairs at all. =)

  11. Avatar
    Bucharest Apartments over 3 years later:

    I would love to see, even help if I can, a modern GUI API for C++. It should probably not be in the standard, but in the standard’s sibling; Boost.

    I know there are several GUI libraries out there, with Qt being one of the better, but I’m just very reluctant to having a company owning the API.

    My idea is that with all years of experience, plus C++0x, a new GUI API could be very clean and intuitive. It’s also important to emphasize that Boost does not need to provide any implementation; just the API. Then several different vendors could profit on selling full implementations, as long as I can swap out one implementation for another just changing a library file. Apartments for rent Bucharest

  12. Avatar
    oxpdffr over 3 years later:

    Excel en PDF Convertisseur s’installe dans votre ordinateur comme un imprimante virtuelle, il supporte convertir tous les formats imprimable en document PDF, tels que Excel(xls, xlsx), TXT, les images (JPEG, GIF, PNG, BMP, EMF, EWF, TIFF), etc, compatible avec Microsoft Office 2003/2007/2010. Huit formats de sortie : PS, EPS, PDF, PNG, JPEG, BMP, PCX, et TIFF, compatible avec Adobe Acrobat 9.0.Télécharger gratuitement Excel en PDF Convertisseur et expérimenter ce logiciel.

  13. Avatar
    iPhone to Mac Transfer over 3 years later:

    The software you can trust to export iPhone music, video and more to Mac.

  14. Avatar
    Pandora over 3 years later:

    if you are not writing lots of automated test cases, and writing them before you write the code that makes them pass.

  15. Avatar
    pandora over 3 years later:

    The beauty of purchasing on the internet is you get to see everything the provides, where in a shop it may be challenging sort even so their inventory to get the right thing. Parents adore gifts which can be unforgettable. Make an effort to current the mom by using a surprise that may be individualized, just as one illustration a diamond ring applying their identify etched inside it. Gold jewelry lead to great items since they immortalize the mom?¡¥s brand inside rare metal. The gold necklace and also a durant creates a fantastic gifts for your mum, as well as presents that happen to be most often disregarded .

  16. Avatar
    pandora over 3 years later:

    Had a great response practically carried out, had been resistant reading through the idea & acquired destroyed through an advert regarding Shipwreck drops. Been ages since I checked throughout here & remaining since the huge internet site changes lsat summer time produced engaging by means of dial-up Painful. I discover situations are very similar. Sleep deprived & jumped more than through the Etsy forums which usually didn’t get myself today… Spend a while stalking for the boards & looking into things available for sale & just lately sold. There have been around 197,000 jewellery entries once i exposed our look (NGHDesigns) in late September. There are over Three hundred,500 now. I’ve got several success & enjoy participating right now there, nevertheless are delighted that is not the way you keep a top above our brains. Some sellers prosper right now there, other people certainly not promote a thing. Even probably the most extraordinary things are hidden inside ton in mere min’s.

  17. Avatar
    Alex Oliveira over 4 years later:

    I think pairs and tuples can be usefull some times.

    Today, I’ve wrote a function with the following signature: std::pair<Vector, Traffic> generate_requests(const Graph& graph);

    This function used to return just a Vector with the weights of the vertices after the generated requests passed through it. But now, I need the information about the generated traffic too. Thus, the function have to return two different things.

    It will not make sense to group both informations in a struct. What name will I give to this struct? They are not two parts of the same thing, they are two different things.

    In the documentation of the function, I’ve wrote something like “This function return two diffent things: a Vector with the weights of the vertices and the information about the generated traffic”. And in the calling code I’ve put:
    Vector weights;
    Traffic requests;
    boost::tie(weights, requests) = generate_requests(graph);

    I agree with the article in most parts. But, I think we cannot stipulate a rule like “tuples are never usefull, never”.

  18. Avatar
    Criminal Records over 4 years later:

    The goal here is to keep code devilishly simple. Sometimes that means having more classes and shorter functions, and better names. Hence, I am with your coworkers on this. Clear is a kind of “good” that matters.

  19. Avatar
    Tenant Screening over 4 years later:

    The goal here is to keep code devilishly simple. Sometimes that means having more classes and shorter functions, and better names. Hence, I am with your coworkers on this. Clear is a kind of “good” that matters.

  20. Avatar
    jaychouchou over 4 years later:

    To be, or not to be- that is a question.Whether ipad bag tis nobler in the mind to suffer The slings and Game Controllers arrows of outrageous fortune Or to take arms against a sea of troubles, And USB Gadgets by opposing end them.E.N.D?

  21. Avatar
    replique louis vuitton over 4 years later:

    Sleep deprived & jumped more than through the Etsy forums which usually didn’t get myself today… Spend a while stalking for the boards & looking into things available for sale & just lately sold. There have been around 197,000 jewellery entries once i exposed our look (NGHDesigns) in late September.

  22. Avatar
    Amy Pratt over 4 years later:

    This one is an informative post. I love it. Thanks. roof nokomis

  23. Avatar
    damper over 4 years later:

    Our company is engaged in the professional manufacturer of damper, air cylinder, oil cylinder, and hydraulic station. The company has many year’s production experience and strong technical power.

  24. Avatar
    okey oyunu oyna over 4 years later:

    it is useful….

    internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.

  25. Avatar
    real estate advertising over 4 years later:

    I love your post Thank :-)

  26. Avatar
    handbags for sale over 4 years later:

    Thank you soooooo much! :)

  27. Avatar
    Discont Louis Vuitton Scarves over 4 years later:

    Thank you soooooo much!

  28. Avatar
    Unique Article Wizard over 4 years later:

    very nice article ! quite helpful for a newbie like me !

  29. Avatar
    beats by dre store over 4 years later:

    , oil cylinder, and hydraulic station. The company has many year’s production experience and strong technical power.high quality headphones new design headphones

  30. Avatar
    Dolce and Gabbana over 4 years later:

    thanks very much for share with us

  31. Avatar
    chaussures over 4 years later:

    It is often detailed that should “ 50 ‘ soon after the” equipped coupled with encouraged together with the Fang-Fang Li, Liu Dong, Huang Ming brand-new legend handsetJimmy Choo Escarpins sandales. Fang-Fang Li were able to move on as a result of Ny University College student Bank concerned with Training video Attempting Business while in the the front without the need of hand back is often Ang Protect; Jimmy Choo Tall Bootsyour ex-girlfriend compact popularity, ‘07 ages youngster exactly who manufacture timeless tomes, “ 17-year-old yowl, ” Jimmy Choo Tall Bootscoupled with made use of within 10 types considering the exact make concerned with its TV cord, prevalent watch, the following turned sailing the initial accolade reward along with the Enthusiastic Head limitation Reward

    the north face

    .

    At this juncture a person’s preparation while in the program “ 50 ‘ after” the next concerned with 2007 have been remaining picked up all over Tokyo, “ Asian Youngster

    north face jakke

    program. ” “ 50 ‘ soon after the” Liu Dong Chen XingchenDiscount Ugg Boots |Discount Ugg Boots gamed outside together with the business expansion considering 1980s track record while in the big vary arrangement China’ ersus marvelous improvements all over couple of a long time, signifying business expansion concerned with 50 youngster right after track record utilizing their love, conduct coupled with likelihood so you might impressive symptoms.canada goose This amazing news flash press reporter determined this, “ 50 ‘ after” is going to be launched all over Tiongkok all over past due Augustcanada goose jakke.

  32. Avatar
    <a href="http://coronerjobdescription.com">Coroner Job Description</a> over 4 years later:

    Nice posts are visible in this blog that to very much enjoyed for the great technology in this blog. It is very excellent info is visible in this blog and the nice services are visible in this website Coroner Job Description|Medical Technologist Job Description|Corrections Officer Job Description|Financial Analyst Job Description

  33. Avatar
    how to become over 4 years later:

    I am How To Become A Hedge Fund Manager very How To Become A President much satisfied by the nice How To Become A Bookie info is visible in this blog and How To Become A Body Builder using the nice technology in this blog How To Become A Federal Agent Thanks a lot for providing the nice info is visible in this blog

  34. Avatar
    how to become over 4 years later:

    This is How To Become A Food Critic very much happy for How To Become Medical Assistant providing How Do You Become A Detective the nice info is How To Become A Better Reader visible in this blog How Long Does It Take To Become A Paralegal I am really How To Become A Broker great services How To Become A Radiologist in this blog and using the nice technology

  35. Avatar
    how to become over 4 years later:

    This website design is really different style in this blog and great technology How To Become A Diplomat in this blog and using the great How To Become A Motivational Speaker services in this blog. I am very much impressed with the nice info is visible in this blog. Thanks a lot for providing How To Become An Alpha Male Review the great info is visible in this blog

  36. Avatar
    Buy Nike Air Yeezy over 4 years later:

    The worst method to forget some one is for getting sitting centerbesidehim knowing you cant have him.

  37. Avatar
    ysbearing over 4 years later:

    Slewing bearing called slewing ring bearings, is a comprehensive load to bear a large bearing, can bear large axial, radial load and overturning moment.

  38. Avatar
    12 casino slots blog over 4 years later:

    I really love the great info is visible in this website that to using the great services in this blog. Thanks a lot for providing the great technology is visible in this blog that to using the great services in this blog.

  39. Avatar
    casino journal topics over 4 years later:

    This is really satisfied by the great info is visible in this blog that to using the amazing technology is visible in this blog. Thanks a lot for providing the great services in this blog.

  40. Avatar
    double bingo only over 4 years later:

    This is very much happy for using the great info is visible in this blog and using the great services in this blog. Thanks a lot for providing the great info is visible in this blog that to using the great technology in this website.

  41. Avatar
    Tips For Bowling over 4 years later:

    I’ve been on such a losing streak that if I had been around I would have taken General Custer and given points.

  42. Avatar
    alwadifa over 4 years later:

    I liked you blog so im going bookmark it with my prefered websites, you have posted an amazing posts so thank you I liked you blog so im going bookmark it with my prefered websites, you have posted an amazing posts so thank you

  43. Avatar
    christian louboutin over 4 years later:

    The professional design make you foot more comfortable. Even more tantalizing,this pattern make your legs look as long as you can,it will make you looked more attractive.Moveover,it has reasonable price.If you are a popular woman,do not miss it.

    Technical details of Christian Louboutin Velours Scrunch Suede Boots Coffee:

    Color: Coffee
    Material: Suede
    4(100mm) heel
    Signature red sole x

    Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Tall Boots, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.

  44. Avatar
    ???? over 4 years later:

    godo @@!111

  45. Avatar
    desrts over 4 years later:

    Comfortably, the article is in reality the greatest on this noteworthy topic. I concur with your conclusions and will thirstily look forward to your upcoming updates

    inder

  46. Avatar
    SpameMeNot over 5 years later:

    sad with the spam :) Nice article.

  47. Avatar
    Backup iPhone SMS over 5 years later:

    Make it possible to backup all stuff including contacts to computer and restore to iPhone when necessary.

  48. Avatar
    mbtshoe over 5 years later:

    Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro

  49. Avatar
    FLV to MP4 Converter over 5 years later:

    I wanted to follow up and allow you to know how , a great deal I treasured discovering your web site today. , all conversion from flv to mp4, flv to video, video to mp4

  50. Avatar
    louboutin sales over 5 years later:

    Tuple Madness and STL in C++ 49 hoo,good article!!I like the post!34

  51. Avatar
    hermes purple bag over 5 years later:

    Ruched leather sack size bags which have a squashy appearance and appear oversized make an appearance against bum bags set to return amid sporty types?

  52. Avatar
    Silicone Molding over 5 years later:

    With more than 20 years of experience, Intertech provides an extensive integrated operational ability from design to production of molds 100% made in Taiwan. Additional to our own mold making factory, we also cooperate with our team vendors to form a very strong working force in Taiwan.

    For the overseas market, we work very closely with local representatives in order to take care of the technical communication and after-sales service to our customers. We also participate in the EUROMOLD & FAKUMA exhibitions and meet our customers every year in Europe. By concentrating on mold “niche markets”, we play a very useful mold maker role from the Far East whenever customers want to develop their new projects. We provide services from A to Z to our customers on a very economic cost and effect basis.

Comments