RubyFlow The Ruby and Rails community linklog

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?

Comments

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 :-)

http://trailblazer.to/gems/operation/2.0/index.html#flow-control

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