views:

175

answers:

5

As I write some scripts, I usually reach a point where my code looks like this :


         end
       end
     end
   end
 end
end

I don't know about you, but this look very ugly to me. Can something be done about this?

+4  A: 

If those inner blocks do something easy to name (and maybe reusable?), why not refactor them into small separate functions ? Then you'd end up with much shorter sequences of end's.

Otherwise another approach is using Python :-)

Andrew Y
I was sure someone would suggest Python :)
Geo
I actually had in mind both Python and Potion [http://github.com/why/potion/tree/master] - but the latter is a bit more of experimental flavour :-)
Andrew Y
+18  A: 

Don't nest your code so much? Refactor to use more methods? Use blocks passed to other routines instead?

Generally speaking, deep nesting is an indicator that a method is getting too complex and should be broken up. It can help for implicit structural documentation too, by naming the inner compound statements according to their refactored methods.

Barry Kelly
+5  A: 

The advice to break up into smaller pieces is good. But if you need a lot of nested blocks like that, you can label the end keywords with comments.

    end # End conditional statement
  end # End method declaration
end # End class declaration

Still ugly, but at least clearer.

The other options previously mentioned are preferable.

Ethan
+1  A: 

Try to use small, testable functions. Not only are your functions and more importantly logic easy to test, but your code becomes way more readable.

+1  A: 

I have seen nested "{ }" blocks and 4-space soft tabs and:

end;end;end;end

I suppose this saves vertical space, but I don't recommend, The above comments on avoiding deep nesting and commenting your block-ending lines are the valid approaches. Maybe deep nesting is to avoid method call overhead for things that need speeding up, but readability almost always trumps that kind of "optimization"

Gene T