![]() |
Articles Feed |
Categories
Archives
- July 2010 (5)
- June 2010 (4)
- April 2010 (3)
- March 2010 (2)
- February 2010 (2)
- January 2010 (1)
- December 2009 (1)
- October 2009 (2)
- September 2009 (2)
- August 2009 (1)
- July 2009 (5)
- June 2009 (2)
- May 2009 (2)
- April 2009 (8)
- March 2009 (7)
- January 2009 (2)
- December 2008 (3)
- November 2008 (5)
- October 2008 (4)
- September 2008 (6)
- August 2008 (4)
- July 2008 (5)
- June 2008 (5)
- May 2008 (4)
- April 2008 (2)
- February 2008 (4)
- January 2008 (2)
- December 2007 (2)
- November 2007 (2)
- October 2007 (2)
- September 2007 (1)
- August 2007 (3)
- July 2007 (1)
- June 2007 (4)
- May 2007 (7)
- April 2007 (2)
- February 2007 (3)
- January 2007 (3)
- November 2006 (3)
- October 2006 (3)
- September 2006 (17)
- November 2004 (1)
Want clean code? Stop using the editor.
by: eric | December 21st, 2007 |
Recently I was adding some accessors to a ruby class on the fly, and I kept getting confused by this block:
eval <<-eof def>
The code isn’t particularly complicated, just creating a quick accessor to get at the underlying hash. Yet I had a couple bugs simply because without the editor to give me hints, the code was that much harder to follow. This turns out to be a blessing in disguise, as I am forced to write extremely clean code just to keep from confusing myself. Opening up the String class cleans this up a bit, and removes duplication:
eval <<-eof def>
There much better. So the next time you think your code isn’t as clear as it could be, or maybe if you think it’s perfect, try reading it without any syntax highlighting. If you can still follow it quickly and easily, then maybe it doesn’t entirely suck.

October 18th, 2008 at 06:32 PM I'm not sure I understand why you need string eval for this - in perl I'd be writing something like
*{$mangled_mode} = sub { my $self = shift; $self->additional_fields ->{payment_modes} ->{$mangled_mode}; };and the $mangled_mode variable would be lexically captured by the sub {} block - can't you use a similar closure trick to clean up the ruby?October 18th, 2008 at 06:32 PM want a readable blog? stop using black text on dark grey background.
October 18th, 2008 at 06:32 PM @Matt: No, in Ruby a def foo ... end block gets evaluated at read time, and foo is treated by the parser as a string literal. There are ways to dynamically define a method that don't involve string evaluation, but they involve a call to a "define_method" method, which is passed a closure containing the code that forms the method body, which can lead to some unfortunate scoping effects.