Robert Klemme
4/21/2006 7:21:00 AM
gmalicki@gmail.com wrote:
> These two snippits of code both do the same thing. One of them uses
> reflection and one does not. The one that uses reflection is a line
> shorter so to me it feels like a better choice. In the #ruby-lang IRC
> channel people told me to "use reflection only when you have to". Is
> that a sane general rule to stick with for Ruby programming ? Is there
> anything wrong with using reflection in this case ? Are there any
> upsides or downsides to either approach ?
Reflection is usually slower. And yes, IMHO you should use it only if
you actually need meta programming capabilities.
> # NIL LOCAL VAR TECHNIQUE
> query = nil
> query = "foo" if config[:scope] == :page
> query = "bar" if config[:scope] == :domain
> raise BrokenConfig if query.nil?
>
>
> # REFLECTION TECHNIQUE
> query = "foo" if config[:scope] == :page
> query = "bar" if config[:scope] == :domain
> raise BrokenConfig unless Kernel.local_variables.member?( "query" )
Don't do either of the two. There are far better idioms available:
query = case config[:scope]
when :page
"foo"
when :domain
"bar"
else
raise BrokenConfig
end
QUERY_MAP = Hash.new {|h,k| raise BrokenConfig, k}.update(
:page => "foo",
:domain => "bar"
).freeze
....
query = QUERY_MAP[config[:scope]]
Kind regards
robert