My Favorite Bad Practices
I can’t truthfully say what level of coder I am. I mean there are moments when I’d say I’ve got an awfully brilliant nugget of code on my hands, but who knows. Brilliant code is sort of hard to notice when you’re chuggin along, you know?
I definitely have some sordid moments. Wanting to finish, wanting to sprint, I yank out one of the following constructs. Bits of code I’m not proud of, but which I love with forbidden love, which must be prefixed with a moment of knuckle-cracking.
rescue as an exception-catching
So, it’s common to use
or in assignment, right? You often see stuff like this:
tmpdir = ENV['TMP'] || "/tmp"
If the environment variable isn’t set, then
tmpdir will fall back to
"/tmp". Perfectly honorable bit of code.
But lately, when my primary data source is possibly volatile (a database or a file or something), I use
rescue in place of
comments = weblog.storage.load_attached( entry_id, "comments" ) rescue 
It feels seedy, ignoring all the possible exceptions that could be thrown deep in the API, but sometimes I just don’t care. I’ll deal with it elsewhere.
puts all over the place.
I’ll be in the middle of a web application using
puts. See, I just used it so much in command-line apps that I just always end up overriding
Kernel::puts or redirecting
STDOUT when the script starts. It’s totally lacksa lazy, huh?
class << STDOUT def write( msg ) unless defined? @puts_log require 'logger' @puts_log = Logger.new '/tmp/my-script.log', 'monthly' end @puts_log.info msg end end
3. Using ERb for everything.
After this weekend, all my C unit tests for Syck are now driven by an ERb template. It totally works, I love it, it’s perfect—it’s a hack. Load YAML n Ruby. Generate C with Ruby. Then
make check. Lotsa three-point turns.
require 'erb' puts ERB.new( File.read( "tests.erb" ), 0, "%<>" ).result