There are times when I debate whether to use one-liners or break them out into more readable blocks. Recently I had a situation where I needed to check certain fields on an object depending on the status of other fields.
Let’s say I have a Book object and I wanted to see if it’s condition is good only if the book is checked in.
Here’s an example:
Book=book.first def is_ok?() if book.checked_in? book.good? && book.barcode.nil? else book.barcode.nil? end end
require 'benchmark'
bools=[true,true,true,true,true]
l_times=[]
c_times=[]
0.upto(bools.size) do |pos1|
0.upto(bools.size) do |pos2|
logic_time=Benchmark.realtime { 1000.times { bools[0] && bools[1] && bools[2] && (bools[3] && bools[4] || !bools[2]) } }
puts "logic realtime: " + logic_time.to_s
control_time=Benchmark.realtime { 1000.times { bools[3] ? bools[0] && bools[1] && bools[2] && bools[3] : bools[0] && bools[1] && bools[2] } }
puts "control realtime: " + control_time.to_s
l_times << logic_time
c_times << control_time
bools[pos1]=false
bools[pos2]=true
end
end
puts "average logic time: #{eval('('+ l_times.join('+').to_s + ')/'+l_times.size.to_s)}"
puts "average control time: #{eval('('+ c_times.join('+').to_s + ')/'+c_times.size.to_s)}"
Here’s the result of one run:
average logic time: 0.00086206080866795
average control time: 0.000861808365466548
I know this test doesn’t go through every boolean case, I just wanted to whip up something fast to give myself a piece of mind. After running this a serveral times, the average times varied, sometimes control would be faster, sometimes logic would be faster. The time difference is basically nil.
Conclusion: Go for readability in a case like this, because the performance differences are not noticeable and readers of your code won’t have to build a boolean table to figure out what’s going on.
Amazon Web Services
“Mad Libs” Style Forms
Luke Wroblewski, Chief Design Architect at Yahoo! and author of “Web Form Design“, published a very interesting post about “Mad Libs” Style Forms and how he improved the conversation of vast.com by 25-40%.
This is how Luke tweaked the contact form:
Read the full post: “Mad Libs” Style Form Increases Conversion 25-40%
I wondered whether there is an easy way to put the labels below the text fields as one knows it fromthe original Mad Libs. This is what I came up with:
The HTML and CSS is fairly easy:
Get the whole code from my Mad Libs Github repository.
Or see it in action
Obviously this is not a guarantor for a 40% conversion increase. But it smells like fun a/b testing, doesn’t it?