Now 'and' for something completely different. 90

Posted by Uncle Bob Thu, 26 Jun 2008 18:16:00 GMT

My son Justin is working as a Ruby apprentice for my son Micah at 8th light. We were sitting at the kitchen table, and he showed me a function he was writing. In the midst of the function I saw this:

handle_batch(item) and display_batch(item) while items_remaining?

I looked hard at this and then I said: “Justin, I don’t think you understand what and does.

He said: “I think I do.” and he pointed me to a website which showed 21 Ruby tricks “you should be using in your own code.”

Trick #9 was the use of the and keyword to couple statements together to make “one liners”. It was billed as a trick that [cough] “more confident” Ruby programmers use.

So I got the pickaxe book out and looked up the and keyword. I showed Justin where it said that the second clause won’t be executed if the first clause is false (or nil!) So if handle_batch ever returned nil, then display_batch would never be called.

Warning bells were going off in my head. This was clearly an unintended use of the and keyword that could have rather nasty repercussions. I thought it was somewhat irresponsible for a website that boasted expertise in programming to tell people they should be using a dangerous stunt like this.

However, handle_batch did not return nil, so the and worked well enough in this case; and we had more to do. So I made my point to Justin and then we kept working, leaving the and in place.

An hour later we were making changes to a function. Suddenly a whole bunch of our tests broke. (You know what I’m going to say, don’t you?) The failure mode didn’t make any sense. Suddenly a whole bunch of processing simply wasn’t getting done.

It was Justin who said: “Wow, I’ll bet it’s that and. And it was. The change we had made had indirectly caused handle_batch to return a nil.

OK, this was a fun little story. You might think the moral is “don’t use and for one-liners” or “don’t trust websites that claim expertise”. Yes, those would be good conclusions to draw. But I’m concerned about something else.

The “and trick” is clever. In programming, clever != smart. (OK, sorry, that was clever…) Using a keyword like and in a manner for which it was not intended, and in a way that is not guaranteed to work in all cases, is risky. It bothers me.

By the same token it bothers me that so many Ruby programmers use the ||= trick for lazy initialization. I know it works. I know it’s a standard idiom. I’m not trying to stop people from doing it. Hell, I use it too because it’s become a standard idiom. But it bothers me nonetheless because it entered our vocabulary of idioms because it was clever trick; and clever little tricks have a way of turning into nasty little surprises.

Ruby is a fun and powerful language. But that doesn’t mean we should go out of our way to be clever. We shouldn’t be eager to adopt quirky little idioms and erudite little stunts just because they are cute, or neat, or nifty. Code is hard enough to understand without having to think sideways through the next novel application of the ?: operator.

Professionals write clear and clean code. They use their language well. They use their language efficiently. But they don’t aspire to be master tricksters. Rather, they prove their professionalism by writing code that needs no explanation.

Comments

Leave a response

  1. Avatar
    yachris 1 day later:

    Three things:

    1. You’re absolutely right about ‘clever’ code. I once read a Randall Schwartz article ostensibly introducing beginners to Perl… and having programmed Perl for several years at that point, I could not figure out what his code was doing without reading the article twice. It was that obtuse.
    2. Your link to 8thlight.com is broken.
    3. Do you think it entirely ethical to have a blurb on your son’s website with no disclaimer? Unless it’s some other Bob Martin…
  2. Avatar
    Myles Byrne 1 day later:

    Thanks for writing this up. I had been guilty of using the and keyword to create one-liners as I always assumed && was the short-circuit form of and. As you’ve pointed out, they’re both short-circuit, and besides a subtle precedence difference are essentially aliases to each other.

    The & operator (single ampersand) would execute both statements:

    handle_batch(item) & display_batch(item) while items_remaining?

    While the above is arguably just as tricky it does have the advantage of being familiar to anyone who has done some bash scripting.

  3. Avatar
    Rimantas 2 days later:

    What if the second action should be performed only if the first action returns not nil? And is very apropriate in this case. Like “find something and then display it”. If you find nothing you cannot display it, right?

    I do not get your complain about ||= at all. I’d arugue that this is not tricky, no quirky and makes code easier to read once you are familiar with the idiom. With logic like this we should dismiss C altogether because it has pointers. Imagine, what you can do with that, oh my!. Dumbing everything down to the lowest common denominator is not smart nor clever.

  4. Avatar
    unclebob 2 days later:

    .bq Dumbing everything down to the lowest common denominator is not smart nor clever.

    Agreed. However, using language features for unintended purposes is also suspect.

    As I said, ||= has become a standard idiom, so I have no aversion to it, and use it myself. I just don’t like the way it became a standard idiom…

  5. Avatar
    Andrew Walker 14 days later:

    Great example. I have been bitten badly by ‘clever’ code over the years, some much worse than others. Each time it bites, it hurts because its you who looks bad when it takes a little while to fix something that should be ‘simple’/a ‘quick fix’.

    Undoubtedly the ‘clever’ person who put it in place could fix it quite quickly, but how many times has that person conveniently moved on.

    Many people in this business like being clever, and that is one of the toughest challenges. Its almost a prerequisite that this kind of lesson be learned the hard way – as in your example. Leave the offending code in place and teach/coach about the perils of employing clever techniques. Having said that, there is so much literature out there that advocates this kind of thing, you can’t necessarily blame people. Guess thats the reason I like to have experienced folk around.

    Looking forward to your book.

  6. Avatar
    Tony Morris 14 days later:

    Side-effects and laziness do not mix. Welcome to programming language theory. Oh, and well done on reinventing monads ;)

    http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html

  7. Avatar
    agnoster 14 days later:

    We shouldn’t eschew the use of idioms because some people may use them incorrectly. As was pointed out, that would pretty much rule out pointers. I use “A and B” (or “A && B”, depending on language) specifically because the short-circuit is the logical thing. If you’re not intending that behaviour, it’s not because you’re using a dangerous idiom – it’s because you’re using a perfectly natural idiom incorrectly. The fault, dear Brutus, lies not in the stars…

  8. Avatar
    James Justin Harrell 14 days later:

    It is a well established and perfectly acceptable practice to use ‘and’ operators in this manner when the short-circuiting behavior is desired. This is often used in shell scripts where you don’t want to execute certain commands if a previous command failed. This practice is far too old to be considered clever anymore.

  9. Avatar
    Matt S Trout 15 days later:

    And this is why perl provides the comma operator (ruby may, I didn’t check). Consider, for example

    (warn(“foo\n”), warn(“bar\n”)) for 1..2;

    at my Devel::REPL prompt this gives

    foo
    bar
    foo
    bar

    and the comma shows every indication of clearly being a separator; & is a bitwise operator with a return value you might care about, and as such doesn’t really express the intent of the code.

  10. Avatar
    Charles 15 days later:

    Well ruby doesn’t have the comma operator, but thankfully (unlike eg python) there is no statement / expression dichotomy. Ie:

    
    a = [1, 2, 3, 4]
    until a.empty?
    p a.shift
    p '-'
    end
    

    vs

    
    a = [1, 2, 3, 4]
    (p a.shift; p a.length) until a.empty?
    

    Ie we just use statement separators inside a sub expression rather than a comma operator.

  11. Avatar
    Michael 15 days later:

    I’m quite fond of the ‘and’ trick. I don’t think it’s clever at all. The short circuiting of ‘and’ is well known in most languages, and if that’s the behavior you want, it’s a concise way to get it.

    In shell scripting and Perl, it’s a basic idiom used pretty much everywhere.

  12. Avatar
    human i tarian 18 days later:

    (Off topic) Hey Bob, now that the Iraqi premier has called for a timetable for the withdrawal of US troops from Iraq, how do you feel about your cheer-leading for the Iraq war of aggression? Changed your mind yet? Or are you still an obstinate old man refusing to let facts affect your arguments?

  13. Avatar
    Christina Bacon 28 days later:

    What, using an operator without understanding what it does can cause problems?! To the juniors defense, the [“tips”](http://www.rubyinside.com/21-ruby-tricks-902.html) site didn’t bother to explain what the operator does.

  14. Avatar
    Piers Cawley 2 months later:

    Personally I only use and and or for explicit flow of control reasons

    filehandle = File.open('whatever') or raise "hell" 
    

    And I tend not to use it so much in my Ruby practice anyway because it isn’t idiomatic in the same way that it is in, say, Perl.

    The rationale is that I want to emphasize the happy path through a method and something like

    unless filehandle = File.open('foo')
      raise "hell" 
    end
    

    breaks the flow of the method in ways I’m not happy about.

    I don’t like ||= overly much either, though I use it where I’m certain that ‘false’ isn’t a legal value, but I come from Perl, where the community has been bitten by that one sufficiently often that more recent versions have added the // operator which checks for definedness rather truthiness.

  15. Avatar
    Daniel Brolund 3 months later:

    I think your son did the right thing. In a way… :-)

    Isn’t the real problem that computer science, in its use of boolean algebra, has hijacked the “and”-word (and “or” for that matter) to make it mean something that doesn’t make sense in a spoken language?

    As an illustration, a programmer friend of mine answers questions like “Should we eat now or should we wait a while?” with a simple “Yes.”. :-)

    Logically correct, but it really doesn’t help…

  16. Avatar
    Tim Ottinger 3 months later:

    My favorite saying is “one point of clear is worth two hundred points of clever”. It is clearly unwise to make code unclear, but in the passion for novelty that can be forgotten.

    It’s even worse if a local hero (or worse, a distant hero) uses tricks. Surely any sufficiently advanced science is indistinguishable from magic, but if your code looks like magic then there’s something wrong.

    Also note that cleverness is something that new programmers cherish and collect, but it smells mighty funny to us older guys.

    God save us from being clever.

  17. Avatar
    Tekme 5 months later:

    If I remember correctly, Uncle Bob wrote in his Agile Software Development book that resposibilities should be put in thier own classes on a need-to basis (at least for the non-trivial cases). That is, you shouldn’t try to define the responsibilities of establishing a connection or forming your SQL until you find (the hard way) that your design suffers from the fact that the class has more than one reason to change.

  18. Avatar
    Tekme 5 months later:

    If I remember correctly, Uncle Bob wrote in his Agile Software Development book that resposibilities should be put in thier own classes on a need-to basis (at least for the non-trivial cases). That is, you shouldn’t try to define the responsibilities of establishing a connection or forming your SQL until you find (the hard way) that your design suffers from the fact that the class has more than one reason to change.

  19. Avatar
    gothic prom dresses 8 months later:

    Do you think it entirely ethical to have a blurb on your son’s website with no disclaimer? Unless it’s some other Bob Martin

  20. Avatar
    acai berry benefits 8 months later:

    If I remember correctly, Uncle Bob wrote in his Agile Software Development book that resposibilities should be put in thier own classes on a need-to basis (at least for the non-trivial cases). That is, you shouldn’t try to define the responsibilities of establishing a connection or forming your SQL until you find (the hard way) that your design suffers from the fact that the class has more than one reason to change.

  21. Avatar
    http://ipotpal-bg.net about 1 year later:

    Great information

  22. Avatar
    Kooba Handbags about 1 year later:

    Living without an aim is like sailing without a compass. with a new http://www.handbags4buy.com/ idea is a crank until the idea succeeds.

  23. Avatar
    moncler clearance about 1 year later:

    Very quietly I take my leave.To seek a dream in http://www.edhardy-buy.com/ starlight.

  24. Avatar
    jewellery about 1 year later:

    I am dreaming for,I am happy to see this.

  25. Avatar
    r4 over 2 years later:

    thank you for sharing with us

  26. Avatar
    Blown film extrusion over 2 years later:

    it is helpfull to us

  27. Avatar
    carmeron over 2 years later:

    So I got the pickaxe book out and looked up the and keyword. I showed Justin where it said that the second clause won’t be executed if the first clause is false (or nil!) So if handle_batch ever returned nil, then display_batch would never be called.

  28. Avatar
    cheap chi flat irons over 2 years later:

    best deals on original chea chi flat irons with some new arrived.

  29. Avatar
    briefcase factory over 2 years later:

    entice for my son Micah at 8th light. We were sitting at the kitchen table, and he

  30. Avatar
    ugg bailey button triplet over 2 years later:

    It is a precious commodity.

  31. Avatar
    Bvlgari Jewelry over 2 years later:
    1. You’re absolutely right about ‘clever’ code. I once read a Randall Schwartz article ostensibly introducing beginners to Perl… and having programmed Perl for several years at that point, I could not figure out what his code was doing without reading the article twice. It was that obtuse.
  32. Avatar
    dedicated server India over 2 years later:

    I found your website perfect for my needs. It contains wonderful and helpful posts. I have read most of them and got a lot from them. To me, you are doing the great work.

  33. Avatar
    Pandora over 2 years later:

    and he showed me a function he was writing. In the midst of the function I saw this

  34. Avatar
    wart-off.net over 2 years later:

    Would definitely like to read some more update.

  35. Avatar
    http://www.blacktowhiteiphone4.com over 2 years later:

    I want iphone 4 white as my christmas present!

  36. Avatar
    dvdsoft over 2 years later:

    With the right tool, you can easily burn mp4 to dvd and itunes to dvd. Also, you can use drm removal tool to remove drm protection from itunes, zune, amazon legally. wmv to dvd, mov to dvd, mp4 to dvd, itunes to dvd

  37. Avatar
    US Criminal Record over 3 years later:

    Professionals write clear and clean code.

  38. Avatar
    Deal or no Deal over 3 years later:

    Thanks a million and please keep up the fabulous work. Regards Kevin

  39. Avatar
    Bingo over 3 years later:

    To increase the page-rank of your web-page keyword density is an important factor. So it becomes very crucial to understand and manage it to get high page rank in search engines and for the search engine result page. I am only giving you the advice to increase your keyword density.It will provide great benefit to you.

  40. Avatar
    electric winch over 3 years later:

    Thanks for writing this blog post, it was informative, enjoyable, and most importantly – a good length!

  41. Avatar
    shaded pold motor over 3 years later:

    Classic exposition, I have also mentioned it in my blog article. But it is a pity that almost no friend discussed it with me. I am very happy to see your article.

  42. Avatar
    Criminal Check over 3 years later:

    Professionals write clear and clean code.

  43. Avatar
    wastewater management over 3 years later:

    I think your both sons will get their goal. Working with ruby code is a good experience and also knowledgeable for the persons who like to work in the web development site.

  44. Avatar
    willamstelin over 3 years later:

    Yes, You are absolutely right. I am also a developer and working on Ruby. By using clear and clean code can work effectively. Very well discussion I have also taken few thinks from here.Thanks. weightloss for women

  45. Avatar
    Previa For Sale over 3 years later:

    It was great experience to read this site article i found it very useful and informative….. Previa For Sale

  46. Avatar
    dvdsoft over 3 years later:

    With the right tool, you can easily burn mp4 to dvd and itunes to dvd. Also, you can use drm removal tool to remove drm protection from itunes, zune, amazon legally. wmv to dvd, mov to dvd, convert mp4 to dvd, itunes to dvd

  47. Avatar
    Tenant Screening over 3 years later:

    I know it works. I know it’s a standard idiom. I’m not trying to stop people from doing it. Hell, I use it too because it’s become a standard idiom. But it bothers me nonetheless because it entered our vocabulary of idioms because it was clever trick; and clever little tricks have a way of turning into nasty little surprises.

  48. Avatar
    Criminal Records over 3 years later:

    The comma shows every indication of clearly being a separator; & is a bitwise operator with a return value you might care about, and as such doesn’t really express the intent of the code.

  49. Avatar
    cyclonesolutuins@hotmail.com over 3 years later:

    another great read! thanks! im always looking out for your next blog, they seem to get better and better thankyou! Tea Makers

  50. Avatar
    dswehfhh over 3 years later:

    We are the professional t-shirts manufacturer. t-shirts supplier. t-shirts factory, custom t-shirts.

  51. Avatar
    Sunglass over 3 years later:

    Women Replica Sunglass at cheap discount price

  52. Avatar
    Mexico City Cheap Hotels over 3 years later:

    When planning your trip to Mexico,choose the best!

  53. Avatar
    Sharon Tweed over 3 years later:

    I like this post. A really good one. Thanks guys. roofing englewood

  54. Avatar
    Mulberry Outlet over 3 years later:

    …While I was searching for some related stuff I found this post…

  55. Avatar
    okey oyunu oyna over 3 years later:

    nice article thank you …

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

  56. Avatar
    mulberry bags over 3 years later:

    When planning your trip to Mexico,choose the best!

  57. Avatar
    mulberry bags sale over 3 years later:

    choose the best!

  58. Avatar
    real estate advertising over 3 years later:

    I love reading your post :-)

  59. Avatar
    austin bail bonds over 3 years later:

    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have enjoyed reading. Nice blog, I will keep visiting this blog very often.

  60. Avatar
    christian louboutin shoes on sale over 3 years later:

    Have the christian louboutin patent leather pumps is a happy thing. Here have the most complete kinds of christian louboutin leather platform pumps.

  61. Avatar
    Jewellery over 3 years later:

    Online UK costume and fashion jewellery shop with, Online UK costume and fashion jewellery shop with, Online UK costume and fashion jewellery shop with, Online UK costume and fashion jewellery shop with, Online UK costume and fashion jewellery shop with,

  62. Avatar
    beats by dr dre headphones over 3 years later:

    Beats by dr dre studio with look after talk in white. extra attributes on Monster Beats By Dr. Dre Pro Headphones Black a specific tri-fold design and design and carrying circumstance which make for compact and uncomplicated safe-keeping when not in use. Beats by dr dre solo .

  63. Avatar
    Commercial photography over 3 years later:

    All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts. Thanks

  64. Avatar
    graham tx over 3 years later:

    It is nice to find a site about my interest. My first visit to your site is been a big help. Thank you for the efforts you been putting on making your site such an interesting and informative place to browse through. I’ll be visiting your site again to gather some more valuable information. You truly did a good job.graham tx

  65. Avatar
    graham tx over 3 years later:

    Really impressed! Everything is very open and very clear explanation of issues. It contains truly information. Your website is very useful. Big buddy in the picture.Thanks for sharing. Looking forward to more!graham tx

  66. Avatar
    graham tx over 3 years later:

    I definitely desired to deliver a quick concept to thank you for the nice tips and hints you’re posting on this website. My time-consuming internet appear up has now been rewarded with helpful strategies to exchange with my family and friends. I ?d claim that we readers fact are truly blessed to dwell in a helpful community with incredibly some great individuals with insightful points. I really feel really grateful to get discovered the webpage and appear ahead to a lot of additional entertaining moments reading right here. Thanks a good deal again for a good deal of things.

  67. Avatar
    mp3 converter over 3 years later:

    Good Information Very nice post.

  68. Avatar
    Bowtrol over 3 years later:

    Blog posts about wedding and bridal are always rare to find , at least with great quality,you qualify for a great blog post writer title,kep the great job happening

  69. Avatar
    Jades Company over 3 years later:

    nice blog thanks for the comments i wanna share this one especially to all applicants who need a best resume

  70. Avatar
    beats by dre store over 3 years later:

    for a great blog post writer titlehigh quality headphones new design headphones,kep the great job happening

  71. Avatar
    dvd ripper over 3 years later:

    good post, i think so.Thank you!

  72. Avatar
    dvd ripper over 3 years later:

    good post, i think so.Thank you!

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

    This is very amazing info in this blog that to very much enjoyed for this info in this blog. Coroner Job Description|Medical Technologist Job Description|Corrections Officer Job Description|Financial Analyst Job Description

  74. Avatar
    how to become over 3 years later:

    I am How To Become A California Resident very How To Become A GAME WARDEN much happy for using How To Become A Real Estate Appraiser the great technology How To Become A Politician is visible in this blog and sharing the nice services in this blog

  75. Avatar
    how to become over 3 years later:

    I am regular How To Become A Fireman visiting the nice info is How To Become A Corporation visible in this blog that to How To Become A Wedding Consultant providing the updated How To Become A Travel Writer info is visible in this blog. Thanks a lot for providing the great info is visible in this blog

  76. Avatar
    how to become over 3 years later:

    I had How To Become An Animal Cop really great technology How To Become Cameraman is visible in this blog and How To Become A Dominatrix using the nice services in this blog How To Become A Hair Model This how To Become A Travel Agent From Home is very much How To Become A Fashion Photographer happy for using How To Become Neurologist the nice services in this blog and really wonderful technology is visible in this blog

  77. Avatar
    ysbearing over 3 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.

  78. Avatar
    bingo journal topics over 3 years later:

    I had really admired for the great info is visible in this blog that to sharing the great technology in this blog. Thanks a lot for providing the great info is visible in this blog.

  79. Avatar
    online poker just over 3 years later:

    This is very much happy for using the great approach is visible in this blog that to the way of presentation is really cool. Thanks a lot for providing the great info is visible in this blog.

  80. Avatar
    CASINO SINAZ over 3 years later:

    I am very much satisfied by the great technology in this website that to sharing the great services in this blog. Thanks a lot for providing the amazing info is visible in this blog that to sharing the great services in this blog.

  81. Avatar
    CASINO DAILY NEWS over 3 years later:

    Thanks a lot for providing the great info is visible in this blog that to sharing the great info is visible in this blog. I am very much inspired the great technology in this blog.

  82. Avatar
    Tips For Bowling over 3 years later:

    This dullness of vision regarding the importance of the general welfare to the individual is the measure of the failure of our schools and churches to teach the spiritual significance of genuine democracy. Henry A. Wallace

  83. Avatar
    flac converter over 3 years later:

    Thank you for sharing, I’ll definitely dig deeper into it.

  84. Avatar
    flac converter over 3 years later:

    good post, i think so.Thank you!

  85. Avatar
    alwadifa over 3 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

  86. Avatar
    Beats By Dre Canada over 3 years later:

    And she was the awards wear a by fresh beef made of meat pack, again making her a topic of the world.

  87. Avatar
    Backup iPhone SMS over 4 years later:

    Backup iPhone SMS to computer and you can import the contacts file to email address book or other mobile phone. good luck.

  88. Avatar
    bladeless fans over 4 years later:

    Now ‘and’ for something completely different. 87 good post79

  89. Avatar
    louboutin sales over 4 years later:

    Now ‘and’ for something completely different. 88 hoo,good article!!I like the post!77

  90. Avatar
    beach cruiser bicycles over 4 years later:

    It has an extended frame and forward pedaling which make it an exceptionally comfortable cruiser for taller people.

Comments