From: Hal Fulton Date: 2004-07-17T05:21:17+09:00 Subject: Dynamically replacing methods for efficiency I have an idea here, but I'm afraid of crossing the line from cleverness to madness. Imagine you have a class with methods whose behavior changes based on various attributes. For example, I'll name this method "action"; suppose that in general, it just calls do_this and do_that. def action do_this do_that end But now suppose we enable things like a debug mode and a trace mode and logging and a configurable delay and such: def action STDERR.puts "Entering action" if @trace STDERR.puts "before do_this: foo = #@foo" if @debug @log.puts "#{Time.now}: Useful info" if @log sleep(@delay) if @delay do_this STDERR.puts "Returned from do_this" if @trace STDERR.puts "after do_this: foo = #@foo" if @debug @log.puts "#{Time.now}: More useful info" if @log do_that STDERR.puts "Returned from do_that" if @trace STDERR.puts "after do_that: foo = #@foo" if @debug @log.puts "#{Time.now}: Still more useful info" if @log end Here we've added ten if-statements. If #action is called frequently, performance will degrade even if these special attributes are not set. But suppose for example we fixed the "trace" setter so that when it was set, it aliased "action_trace" to "action", where the former is something like: def action_trace STDERR.puts "Entering action" do_this STDERR.puts "Returned from do_this" do_that STDERR.puts "Returned from do_that" end There would also be versions like: action_log, action_debug, not to mention (here's where it gets hairy) things like action_debug_log, action_debug_trace, action_debug_trace_log, and so on. On the one hand, I appreciate Ruby because I *can* do this sort of thing. On the other hand, if the logic for #action changes, how many pieces of code will I find myself modifying? Another possibility is: When a special attribute is changed, write the method code to a file and load that file. This at least would keep all the logic in one place. Please: Express your opinions. Hal