A while ago, I was working with a problem in C# where where our code would get deadlocked, and since someone must die or several must starve, I thought it
would be nice to just toss a "try again if deadlocked"
statement into the exception handler. I muttered this thought on twitter to
see if there was any language with such a try-catch-try-again-if construct.
A couple of my tweeps responded with what we we're used to using: loops.
Another two mentioned
redo
in Ruby.
redo
is certainly a cool construct (and
underused), but it doesn't do what I want
it to:
begin
raise from_the_dead
rescue
redo
end
Ruby responds, "tryredo.rb:35: unexpected redo." As you might know, you need to use a loop:
class Zombie
def initialize
@starving = true
@last_feeding = DateTime.new
end
def eat(bodypart)
@starving = (DateTime.now - @last_feeding) * 10_000_000 > 3
starving_enough_to_reconsider = @starving && rand > 0.5
unless starving_enough_to_reconsider || bodypart == "braaaiiinzzz"
raise "Zombies don't like #{bodypart}"
end
puts "Mmmmm... #{bodypart}"
@starving = false
@last_feeding = DateTime.now
end
end
zombie = Zombie.new
["feet", "stomach", "intestines", "braaaiiinzzz"].each do |bodypart|
begin
zombie.eat bodypart
sleep 1
rescue
puts $!
redo
end
end
So I'll ask to this larger audience:
Suppose I have a zombie who only
really likes eating braaaiiinzzz. Most of the time, he gets exactly
what he wants. But every so often, we try to feed him some other body part. Now, if he's really hungry, he
eats it. We might only have fingers available at the time, so I want
to try to feed him fingers again until brains are available or until he's hungry enough to eat the fingers.
I know that conceptually this is just a loop even if we don't explicitly code it. But does your language have a
try again
? What do you think the merits or demerits of such an approach would be? Is it just a harmful
goto
?
My zombie is hungry and waiting. Rather impatiently I might add.
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
cool update.
Posted by Tracy B.
on Nov 05, 2020 at 01:25 AM UTC - 5 hrs
Leave a comment