Exceptional Flow Control

Posted: Sat, 7 July 2007 | permalink | No comments

(or: finally, a use for ActiveRecord#save!)

I recently found Rescue To The Rescue!, a short article on structuring your Rails controllers differently.

Today, I started using it in some code I was writing that I think really benefitted from the change. The code was a big case that did things like this:

 case some_variable
   when 'X'
     process-based-on-X
     if save
       post-processing
     else
       throw_an_error
     end
   when 'Y'
     process-based-on-Y
     if save
       some-other-post-processing
     else
       throw_an_error
     end
   when 'Z'
     process-based-on-Z
     if !save
       throw_an_error
     end
 end

In each case, the pre-save processing was unique, and -- more importantly -- the action to take after a successful save was different, so I couldn't just save-and-handle after the case statement. However, the throw_an_error code was the same in each case, so I just changed the code to do this:

 begin
   case some_variable
     when 'X'
       process-based-on-X
       save!
       post-processing
     when 'Y'
       process-based-on-Y
       save!
       some-other-post-processing
     when 'Z'
       process-based-on-Z
       save!
   end
 rescue ActiveRecord::InvalidRecord
   throw_an_error
 end

My mind was blown. Soooo much clearer now. I have an "everything's OK" code path, and a "bugger me, something broke" path, cleanly separated.

But something didn't feel quite right...

And now I know what it is. I'm bothered by the fact that I'm sailing very close to using exceptions as an ordinary, every day flow control mechanism. I think I've convinced myself that, in this case, it's OK, but I'm a little concerned that I might go power-hungry and start using it in places that it really isn't warranted. I guess I'll just have to keep an eye on myself.

Just remember, everyone: save! isn't a dirty word!


Post a comment

All comments are held for moderation; markdown formatting accepted.

This is a honeypot form. Do not use this form unless you want to get your IP address blacklisted. Use the second form below for comments.
Name: (required)
E-mail: (required, not published)
Website: (optional)
Name: (required)
E-mail: (required, not published)
Website: (optional)