Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Improving if statements

by sundialsvc4 (Abbot)
on Sep 18, 2014 at 23:39 UTC ( [id://1101121]=note: print w/replies, xml ) Need Help??


in reply to Improving if statements

Personally, I don’t find the present way of doing it objectionable.   Not at all.   It’s obvious what it’s doing.   However, you could put the keys into a hash and then loop through it ...

my %stuff = ( moo => "cow", test => "blue", dark => "black", white => "light", house => "home", "all things" => "multi", money => "value", ); while (my ($k, $v) = each(%stuff)) { if { $input =~ /$k/ } { change = $v; last; # break out of the loop now }

But is it “improved?”   I probably wouldn’t think so, really, because an if..elsif..else cascade is both extremely readable and easy to change, and you can put the most-common cases right up at the top.   Basically, unless you have a compelling reason other than vague thoughts of “efficiency” to change the code as it is now, I’d move on to the next to-do ticket.

Replies are listed 'Best First'.
Re^2: Improving if statements
by choroba (Cardinal) on Sep 18, 2014 at 23:45 UTC
    Not at all? Ever heard of the "DRY" principle? Also, what if one of the ifs compared $iten instead of $item? Do you find it readable?

    BTW, your solution doesn't preserve the order of the tests, so words like "darkwhite" might return a different result than in the OP.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Presumably the programmer or others on the team are paying attention to typos, and is writing test cases for every case to prove that the code works and that it continues to do so.   Mmmmmm...?

      No matter how you did it, there will always be someone else out there who will not only say that you did it “wrong,” but will also insist that the team should spend its time re-writing code that works.   (A practice that Warren Buffett refers to as “sucking your thumb.”)

      On the one hand, if you truly do have “choose this word if that word appears,” as in this case, some sort of loop-based, “run through this list,” algorithm makes good sense ... and I briefly suggested one.   But on the other hand, sometimes the latest request (that cannot be denied) from The Marketing Department throws a monkey-wrench ... an exception to the rule, any slight twist that makes one case a little different from all the rest ... that can make “too-clever” logic turn into a quagmire.   And you can’t anticipate (Marketers are from Jupiter ...) what they might come up with someday, when you write the original version.   Sometimes, a coding style that is, “frankly, butt-ugly,” wins because it is more maintainable.

      To touch on “maintainability” once more:   what if the third case, and only the third one, for some reason had to be different from the rest?   How much of the existing, tested code would have to be changed?   How many of the other, already known-to-be working cases would be impacted?   How much of that block of source-code would have to be touched, whether-or-not it had to do “with case number three?”   If you were too-clever, the answer would be, “all of them, all of it,” because you wrote the code in such a way that the handling for all of the cases was coupled together.   Because the code “cleverly” reduces all of the cases into one, it “cleverly” treats all cases in the same way, but, in so doing, it cannot treat any of them in even a slightly different way.

      “Right or wrong?”   “Better or worse?”   Well, it depends.™   It’s not entirely a matter of “principles.”   You do the best you can, and then the men from Jupiter come along to screw it all up ...

        Why make the job harder by adding a large pile of additional potential typos?

        There are always cranks to complain about everything. That doesn't mean you shouldn't try to do things well. Someone will complain no matter which side of the utensil drawer your spoons are on, but that doesn't mean you should throw them in randomly.

        When things get a bit more complicated, then you add to the data structure. Instead of a simple hash of lookups, have a hash of hashes which include the lookup value and a type. When you have a one-off exception case, add a new type, and handle that. If it isn't a new type of thing, then you trivially add it to the list of things to check instead of copying a block of code.

        This is what requirements and experience are for. Keep it simple with a fixed block and save time now, or make it flexible as an insurance payment now to protect against future additions. For best results, keep the flexibility options in mind while you write the simple case, and make it modular enough that refitting flexibility in later is as easy as tacking an elsif condition on. Either way you go, you don't need to repeat yourself if you use the right data structure.

        You don't have to compromise quality or maintainability on this one.

Re^2: Improving if statements
by Anonymous Monk on Sep 19, 2014 at 13:11 UTC

    This algorithm returns random results. Hash ordering is random.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1101121]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2024-04-18 09:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found