What happens when your code breaks in production? If you have Honeybadger you'll be alerted with crucial details like the error location, the data being processed and the affected users. So you can deploy a fix quickly and get back to coding. Learn more.

RubyFlow The Ruby and Rails community linklog


The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Forget conditionals, use the Rail way

Most of the time, with growing uncertainty, code goes rightwards. Nested conditions are difficult to read and error prone. The real intent is to check success/failure path, so why not make it clear?


I agree with making it clear but the solution should not be exceptions because they were not designed for application flow. The “Exceptions should be exceptional” mantra exists because they are expensive and slow. If you don’t need a stack trace for Rails validation errors (or authentication, authorization etc) why spend resources and time only to throw it away.

I think all these methods should return a result you can check before proceeding to the next step not raising exceptions all over the place. There are a bunch of patterns you could use to golf your code without using exceptions to jump around.

expensive and slow.

cost of using exceptions for control flow compared to one SQL statement: https://gist.github.com/paneq/a643b9a3cc694ba3eb6e

Robert you need to benchmark the difference between an exception and a conditional statement since that’s what the article suggested. The SQL will be run regardless so the performance of a database query is irrelevant.

https://simonecarletti.com/blog/2010/01/how-slow-are-ruby-exceptions/ http://codesthq.com/blog/2015/exceptions-are-killing-your-apps-performance.html

Even if they somehow make raising an exception and catching it perform as quickly an inbuilt conditional statement you still shouldn’t be using exceptions for flow control in Ruby.

For example the article introduces glaring bugs like catching StandardError rescuing more than just the validation errors the author intended but also general programming errors like calling methods on undefined variables.

rescue StandardError => e

If he rescued each individual type of exception that might be thrown by Rails the code will end up longer and even more unreadable.

To be clear I like that the author has identified all his nesting is an issue and the motivation to remove it. I just don’t like any of the proposed solutions.

That’s Railway pattern - in Trailblazer since version 2 :-)


Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in