I once read somewhere that you should only use the if or unless conditionals at the end of a statement if that statement usually occurs (i.e., the condition usually passes). Otherwise, you should put the conditional at the beginning. For example, this is good behavior, since @post would normally be an ActiveRecord object:
first_comment = @post.comments.first unless @post.nil?
While this is not, since @post is rarely nil:
redirect_to :action => 'list' if @post.nil?
This makes sense for readability, but I find myself writing one-off statements with conditionals at the end, similar to the one above, because I don’t want to clutter up my code with a three line block:
if @post.nil?
redirect_to :action => 'list'
end
The alternative that I have deemed “most correct” is to simply write this as one line. This can be done using the following syntax:
if @post.nil? then redirect_to :action => 'list' end
You can alternately replace then with a colon (:) but I think writing then is cleaner since it makes your code read like English. (I do wish I could get rid of that pesky end.)
So in the end, would you agree with this assessment, or should I just ignore that advice and simply use conditionals at the end of the statement?




March 5th, 2007 at 09:21 PM Yes I would say I use that last syntax quite a bit. If the expressions are simple, it ends up looking better. If you have multiple branches (else if) or if the expressions are complicated in any way, it could get ugly. Speaking of which, does ruby code end up in smaller, more manageable chunks, from smaller methods to less complex expressions, all on its own, or is it just me?
March 6th, 2007 at 08:52 AM Yes, if the condition is complicated, then a 3+ line block make sense. For multi-line conditionals, I bring back use of the @then@ keyword for readability as well: To some degree, Ruby helps keep your code simple. I think this is because you have more direct tools to accomplish what you need to do, like blocks and methods like @#collect@ and @#inject@. However, keeping your code comprehendible often takes conscious effort-- in other words, I've still seen some pretty badly written Rails code.