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.
1. Using rescue
as an exception-catching or
.
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 or
.
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.
2. Going 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
flgr
bogbog
rescue doesn’t rescue all the possible exceptions, only StandardError and subclasses
why
bogbog: so glad you came up from the swamps to say so.
batkins
flgr: How does breakpoint work in the context of a web application? Do you have to be running your code as a WEBrick servlet?
flgr
You simply require ‘breakpoint’ and Breakpoint.activate_drb() which activates a DRb server at a default port that the breakpoint_client also defaults to. Then you run ruby breakpoint_client and you are ready to hit.
Comments are closed for this entry.