Now 'and' for something completely different. 90
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.
Three things:
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 ofand
. 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:While the above is arguably just as tricky it does have the advantage of being familiar to anyone who has done some bash scripting.
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.
.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…
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.
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
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…
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.
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
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.
Well ruby doesn’t have the comma operator, but thankfully (unlike eg python) there is no statement / expression dichotomy. Ie:
vs
Ie we just use statement separators inside a sub expression rather than a comma operator.
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.
(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?
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.
Personally I only use
and
andor
for explicit flow of control reasonsAnd 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
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.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…
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.
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.
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.
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
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.
Great information
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.
Very quietly I take my leave.To seek a dream in http://www.edhardy-buy.com/ starlight.
I am dreaming for,I am happy to see this.
thank you for sharing with us
it is helpfull to us
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.
best deals on original chea chi flat irons with some new arrived.
entice for my son Micah at 8th light. We were sitting at the kitchen table, and he
It is a precious commodity.
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.
and he showed me a function he was writing. In the midst of the function I saw this
Would definitely like to read some more update.
I want iphone 4 white as my christmas present!
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
Professionals write clear and clean code.
Thanks a million and please keep up the fabulous work. Regards Kevin
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.
Thanks for writing this blog post, it was informative, enjoyable, and most importantly – a good length!
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.
Professionals write clear and clean code.
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.
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
It was great experience to read this site article i found it very useful and informative….. Previa For Sale
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
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.
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.
another great read! thanks! im always looking out for your next blog, they seem to get better and better thankyou! Tea Makers
We are the professional t-shirts manufacturer. t-shirts supplier. t-shirts factory, custom t-shirts.
Women Replica Sunglass at cheap discount price
When planning your trip to Mexico,choose the best!
I like this post. A really good one. Thanks guys. roofing englewood
…While I was searching for some related stuff I found this post…
nice article thank you …
internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.
When planning your trip to Mexico,choose the best!
choose the best!
I love reading your post :-)
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.
Have the christian louboutin patent leather pumps is a happy thing. Here have the most complete kinds of christian louboutin leather platform pumps.
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,
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 .
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
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
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
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.
Good Information Very nice post.
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
nice blog thanks for the comments i wanna share this one especially to all applicants who need a best resume
for a great blog post writer titlehigh quality headphones new design headphones,kep the great job happening
good post, i think so.Thank you!
good post, i think so.Thank you!
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
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
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
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
Slewing bearing called slewing ring bearings, is a comprehensive load to bear a large bearing, can bear large axial, radial load and overturning moment.
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.
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.
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.
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.
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
Thank you for sharing, I’ll definitely dig deeper into it.
good post, i think 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 I liked you blog so im going bookmark it with my prefered websites, you have posted an amazing posts so thank you
And she was the awards wear a by fresh beef made of meat pack, again making her a topic of the world.
Backup iPhone SMS to computer and you can import the contacts file to email address book or other mobile phone. good luck.
Now ‘and’ for something completely different. 87 good post79
Now ‘and’ for something completely different. 88 hoo,good article!!I like the post!77
It has an extended frame and forward pedaling which make it an exceptionally comfortable cruiser for taller people.