dflanagan
1/19/2007 9:17:00 PM
On Jan 19, 12:59 pm, ara.t.how...@noaa.gov wrote:
> On Sat, 20 Jan 2007 dflana...@gmail.com wrote:
> > Suppose you've got a simple loop to iterate through an array
>
> > data.each { |x| x*x}
>
> > Now you refactor some code and end up cutting-and-pasting that loop into a
> > method that happens to use x as a parameter. Suddenly your loop behaves
> > differently. x is no longer local to the block and it overwrites the local
> > variable in your method.
> you're quite right. what i fail to see is how a 'local' method changes that
> one bit. consider, say you paste the above snippet into some code that has an
It changes it because you fail-fast with a NameError rather than
possibly introducing a bug that may not be near to the source of the
error.
> 'x' defined 20 lines up, you don't notice and introduce a bug. in order to
> prevent this you are advocating this
>
> local :x do
> data.each { |x| x*x}
> end
>
> so a re-def of x will raise an error. at first glance that seems ok.
> consider this however: one must __know_in_advance__ which vars to declare
> local and which not.
The local vars are the ones that you want to be local in the block. I
think this is always easy. And, when you have to cut-and-paste, you
copy the entire local block, so that the protection it gives you
travels with the code.
> in your example it's the only obivous one but, in fact,
> there are two candidates: 'x' and 'data'. now, in this case we know that we
> do, in fact, require the 'data' var __not__ to be local, but to picked up from
> the current scope. note that it's __precisely__ this ability to do mixed
> scoping which makes blocks useful at all - otherwise we'd all just pass
> stuff around.
>
> perhaps you see where i'm going? in order to use local effectively with even
> a moderately complex peice of code one needs to look at the code and decide
> which vars should be local, which should be block-local (ruby 1.9), and which
> should be scoped normally. all this has to be known __up_front__!
>
> the thing is, if i have to know, as a programmer, up front which vars to
> declare local then i don't have a problem any more! ;-)
>
> so, imho, you are correct in pointing out a source for errors but blocks, like
> all coding contructs, must be weighed by comparing advantages vs. disadvatages
> and the mixing of scopes certainly resides on both lists.
>
> it would be nice if way existed to solve the problem you have underscored, but
> if that solution requires me to do the same amount of work that i had to do
> before to solve it 'manually' then it simply becomes line noise and, as we all
> know, any code you write that you don't have to is simply adding bugs.
>
> my 2cts.
>
> kind regards.
>
> -a
> --
> we can deny everything, except that we have the possibility of being better.
> simply reflect on that.
> - the dalai lama