[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: How to Make a Method Ineffective Efficiently?
From:       "Jason Voegele" <jason () jvoegele ! com>
Date:       2002-04-12 15:37:19
[Download RAW message or body]

> Thanks for the suggestion.  I think it is a pretty good idea when I am
> actually dealing with debugging.  However, what I am dealing with is
> more like tracing:
> 
>     class Trace
>       attr_accessor :active
>       attr_reader :name
>       def initialize (name, active)
>       end
>       def write
>         if @active
>           .... (heavy processing)
>         end
>       end
>     end
> 
>     @tr1 = Trace.new ('ATM Data Flow', true)
>     @tr2 = Trace.new ('Routing Information', true)
>     @tr3 = Trace.new ('TCP Timeout', false)
>     ....
>     @tr1.write (obj1, obj2, ob3)
>     @tr2.write (obj1)
>     @tr3.write (obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8)
> 
> Therefore, these are the problems:
> 1) I cannot define just a single global variable such as $DEBUG
> 2) I cannot define the method with no argument
> 3) When I define the method with variable number of arguments, I think
> the objects will still be passed in the array even though the method
> actually does nothing.
> 4) Doing preprocessing on the code will not work, because the state can
> only be inferred within the code execution, as dictated by the member
> data "@active".

You could define a general "do_if" method that executes a block if some 
condition is true:

def do_if(condition, *args)
  yield(*args) if condition
end

Then your above example becomes:

def write
  do_if(@active) { (heavy processing) }
end

This still suffers from problem #3 though, in that parameters are still 
evaluated regardless of the condition.  To fix that, any method that calls 
do_if could itself take a block to supply its parameters.  For example, 
from your original example:

def print_info
  do_if(@debugging) { puts yield }
end

print_info { "#{obj1} #{obj2} .... #{obj1000}" }

This avoids evaluating the parameters unless necessary.

-- 
Jason Voegele

"We believe that we invent symbols.  The truth is that they invent us."
    -- Gene Wolfe, The Shadow of the Torturer

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic