in reply to Re: Re: problem with variable values
in thread problem with variable values

The issue that you are fighting is locality of reference. Locality of reference means that any given variable is localized as much as possible to a small section of code. See Pass by reference vs globals or RE (tilly) 3: redeclaring variables with 'my' for my attempts to explain why this matters.

The iron-clad rule is just a rule that improves locality of reference. But the rule doesn't start or end there. For instance the other day I had an array of colours that I needed to synchronize between a table and a graph. Now I could easily export the array I used in my graph to the table and it would work. But that wouldn't preserve locality of reference, someone else might do something stupid like put in code somewhere that set that array making it hard to figure out why the colors did not synchronize properly.

So I wrote a function in the graph code that returned a closure which would take in elements going into the table and return them with the appropriate color tag. Much better! Inside the graph code you can see that nobody else is abusing this array. Inside the function there is hidden state, but that is documented and the table code knows all of the calls to that function. (Why didn't I return the array? Because if you run out of colors you cycle, and I found that implementing that bit of internal logic in the table to not be very nice. Besides which, some day that behaviour might change, and it would be good that I have it localized!)

So I had an example where I wrote almost exactly what you wrote above. Which breaks the rule that people learn. But by breaking the rule I believe I managed to achieve the goal of the naive rule...

  • Comment on Re (tilly) 3: problem with variable values

Replies are listed 'Best First'.
Re: Re (tilly) 3: problem with variable values
by sierrathedog04 (Hermit) on Jun 14, 2001 at 00:52 UTC
    Tilly's graphing problem is an interesting example of a case where one would want to use a closure because of a special feature that it has (It is only compiled once). When I first learned about them (on this board) a few months ago I read that closures were useful but I had trouble thinking of a concrete example.

    My understanding is closures also have special features in languages other than Perl. I suspect that the special features of closures first appeared in languages as a result of an oversight, but once they appeared programmers found them useful. If so, closures are an example of a random mutation that survives because it enhances the survival of what it mutates. Kind of like feathers on dinosaurs as they evolved into birds.