Ed Avis wrote:
Shawn H. Corey <shawnhcorey <at> gmail.com> writes:

But then again I never have to invert a hash; when I populate it, I would populate its inverse as well. I would build both data structures at the same time, inserting only the data I need, where I need it.

That's often a good approach.  But in the particular case I was thinking of,
there was some (programmer-maintained, not user-maintained) configuration data
in a hash:

    my %lookup = (Frob => 55, Boo => 66, Grick => 67);

Of course it would be silly to write a %lookup_reverse hash by hand and then
worry about keeping the two consistent.  Better to write it once and invert it.

This assumes that programmers never make mistakes. This source of input, and like all input, should be validated before it is used. And while you're validating it, that is, while you're going through the hash one item at a time, you can build your inverse, just like I said.


Similarly, if you are making a subroutine that takes a hash as input, it is
inconvenient to require your caller to pass both the hash and its inverse.
Indeed, it creates all sorts of opportunities for bugs when somehow the hash
and inverse-hash you are passed aren't consistent with each other.  (Generally
anything that can go wrong will go wrong, sooner or later.)

The bugs show up because of the lack of validation. Or are you thinking that some software upstream causes bugs and you're responsible for catching them? It's a better idea to unit test _all_ the software so it does not create bugs.


Or if your routine gives a hash as output (such as many XML processing or
database modules), it would be seen as a bit weird to return both a hash and
an inverse-hash.  It's a question of taste, but I would prefer to just get one
hash as the return value, and invert it if I need to.

Why on earth would you want to invert an XML file? Sounds like someone is being clever. Remember: clever == hard to understand == costly to maintain.

As for inverting the return from a database, I would get the database to do it. It can take advantage of relationships inside the database that are lost when the data is extracted.


So I don't think it is fair to say that inverting a hash is never needed,
although you can certainly minimize the need for it if you build your own
data structures carefully.


To be specific, I said I never had to invert a hash since I build all the data structures I need while validating the input. And no, I don't pass large data structures around. Either I need only one set at a time, in which case they're globals, or I put them in an object and pass that around.


--
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

My favourite four-letter word is "Done!"

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to