views:

225

answers:

6

something.each do |x|

#lots of stuff

end if some_condition

+3  A: 

I'd personally advocate against that for the pure and simple reason that it is too easy to miss. Even with that shortened version it took me a double-take to realise you had the

if some_condition

at the end

workmad3
what if the "if" condition is on the next line immediately after the "end" keyword and there is a blank line immediately after the "if" condition? In such a case it might be clear(er).
fooledbyprimes
in ruby, that then becomes a separate statement though (and probably a syntax error as it stands).
workmad3
A: 

In the organization I work for we have started to flag such constructs for re-write.

Avdi
A: 

I think the above example is perfectly fine in certain cases where it exists inside of several nested blocks. If the above code is 4 levels deep then you have eliminated another level. Therefore, in certain cases, the above style can actually increase readability. Note we are assuming that there are no more than 20 statements within the block.

fooledbyprimes
If its 4 levels deep with modifiers after the blocks then you've got problems. Refactor your code now before anyone sees it!
RichH
Obviously. It was just an example. 4 levels deep is obviously too deep, perhaps. However, what about 3? What about 2? All I am saying is you can eliminate one level with the construct.
fooledbyprimes
+1  A: 

I almost never use the modifier forms of conditionals because I think there is too much potential for reader confusion. It's like an officer talking to a subordinate:

<sergeant> Your orders are to climb that hill and recon the enemy!
<private> YES SIR!  *begins running up the hill*
<sergeant> ... but only if you have binoculars.

The only time I might consider it acceptable is when the thing modified is so small that the conditional can clearly be seen, e.g.

do loop
  # ...
  next if condition
  # ...
end
Pistos
But I do believe the private should understand that he is ready Ruby. Well if he makes the mistake then the Sergeant is there to teach him.
fooledbyprimes
+1  A: 

Long code block it self is a bad practice, refactor it to more smaller blocks.

Modifier after a long block is a way to hell.

Honza
+7  A: 

I think the popular way is to use statement modifiers only if it is a one-liner. In all other cases, use the normal if style prevalent in C, Java etc.

bail_out if reqd_param.nil?

if its_gonna_be_long then
  long_exec stmt1
  long_exec stmt2
  ....
end
Gishu