It's ok, I used a regex



  • snippet 1:

    for (int i=0; i<tasks.length; i++)
    {
        task[i].run();
    }

     

    snippet 2:

    for (Runnable task : tasks)
    {
        task.run();
    }
    

     

    Which snippet would you prefer?

     

    Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No, because a good compiler will probably produce the same result for both loops.

    Are there situations where using the foreach loop results in a worse software product? Absolutely. Not every situation asks for a foreach loop, but you can probably use one anyway if you really wanted to. If all you have is a hammer...


  • Trolleybus Mechanic

    @Astaedus said:

    Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No
     

     My turn:  Bullshit.

     

    foreach(Foo f : foos)
    {
       if (f.sucks())
       {
          foos.remove(f); // crash!
       }

    }

    vs.


    for(i = 0; i < foos.length; foo++)
    {

       Foo f = f[i];

      if (f.sucks())
       {
          foos.removeAt(i); // no crash  
          i--; 
        }

    }



  • @Lorne Kates said:

    @Astaedus said:

    Is there any situation, any situation, where using the foreach loop results in a better software product than not using it? No
     

     My turn:  Bullshit.

    The real point is that for() and foreach() are not equivalent in the way that if() and ?: are.



  • How about for and while? Would that be a better analogy?

    for (int i=0; i<MAX; i++)
    {
        ...
    }
    

    vs

    int i=0;
    while (i<MAX)
    {
        ...
        i++;
    }
    


  • @Astaedus said:

    How about for and while? Would that be a better analogy?

    No, and stop trying.

    If you want to address the topic at-hand, address the topic at-hand. If you want to make awful analogies, at least make them funny... like use pizza or <a href="http://www.huffingtonpost.com/mark-olmsted/income-inequality-for-dum_b_831394.html?>cats eating pizza</a> or something.



  • @blakeyrat said:

    Maybe next time define the word you pulled out of your ass before using it, and I won't make fun of you with clamp clip art.
    I thought a <font color="#FF0000">clamp</font> is what programmers used to pull a word out of their ass.

     



  • @Xyro said:

    message == null ? returnCode == 0 ? "Successful" : "Error" : StringEscapeUtils.escapeXml(message))
     

    :(
    You're guarding for null on a variable, then do something that doesn't even use that variable, and to top it off, you're mixing processing code with output logic and use a format that's a huge disruption to the visual flow of the output code. I think that's bad.

    I'd do this:

    string outputMessage;

    if (message != null) {
       outputMessage = StringEscapeUtils.escapeXml(message);
    }
    else {
       outputMessage = (returnCode == 0? "Successful":"Error");
    }

    And then you start building the XML.

    I've consolidated output to a single variable, everybody knows what I'm trying to do, and I'm still using a nice ternary for that tiny micro-if where you check for the returnCode.

    (In all honesty, I think wouldn't even bother to mention it if we were working on this project together. I'd just change it and check it in. I'm just making a detailed point because we're here, having the discussion)



  • @locallunatic said:

    Heres one that is a bit closer to what I actually deal with
     

    Structurally, that's perfectly fine in my book, but I think you're trying to cram too much functionality into a single line. You just nested an if clause inside its condition.

    Define what that ternary is supposed to do. Give it a name and put it in a var. Then put that var in the if.

     

    Man, I'm just dishing out code advice left right and center, no?



  •  You know, it's actually rather interesting that the two real code examples we get from those who advocate the ternary, are examples of code that tries to do as much as possible inline on as few lines of code as possible.

    As a reminder: this is not the goal, or any goal at all, when programming. The goal is to write the program. The goal is to keep it understandable for your fellow man.

    If you feel that fewer lines means you get more code on-screen... get a monitor that you can rotate!



  • @dhromed said:

    Man, I'm just dishing out code advice left right and center, no?

    You do the code advice, I'll stick with the philosophy.



  •  @Lorne Kates said:



    @Astaedus said:
    Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No


     My turn:  Bullshit.

    *snip* code proving that for has more uses than foreach *snip*


    Read my original sentence again and try to understand it. Then try again.



  • @Astaedus said:

    Read my original sentence again and try to understand it. Then try again.

    The heuristic of "foreach" implies that it can operate on the objects in-parallel. At least, if the operation has no side effects. (I don't know of any languages/environments that currently do this, but it would be awesome wouldn't it?)

    But, the real point is, for() and foreach() do different things. So it's not even remotely the same situation as if() and ?:



  • @locallunatic said:

    @blakeyrat said:

    Letter-Digit-Letter Digit-Letter-Digit.

    They don't use the letters D, F, I, O, Q, or U.

    (Not a Canadian.)

     

    Thanks, I missed Lorne's tag with a better regex (though apparently it would still allow through bad letters).

    Ohh the possibilities. p0t4t0 then.


  • @blakeyrat said:

    Maybe next time define the word you pulled out of your ass before using it, and I won't make fun of you with clamp clip art. Just FYI.

    I suppose you think "MinMax" is a better name for the function?



  • @Faxmachinen said:

    I suppose you think "MinMax" is a better name for the function?
     

    Int.limit(min[, max]);



  • @dhromed said:

    You know, it's actually rather interesting that the two real code examples we get from those who advocate the ternary, are examples of code that tries to do as much as possible inline on as few lines of code as possible.

    You know that simple [url=http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html]Fizz[/url][url=http://www.c2.com/cgi/wiki?FizzBuzzTest]Buzz[/url] test you can use for weeding out non-programmers? This is totally the best way to write it in Java:


    public class InterviewTest {
    static public String DIV_BY_THREE = "Fizz";
    static public String DIV_BY_FIVE = "Buzz";

    static public void main(String[]] args) {
        for (int i = 1;
            ( check(i % 15, DIV_BY_THREE+DIV_BY_FIVE)
            ||check(i %  3, DIV_BY_THREE)
            ||check(i %  5, DIV_BY_FIVE )
            ||check(0, Integer.toString(i))
            ) && i &lt; 100; i++);
    }
    
    static private boolean check(int mod, String message) {
        if (mod==0) {
            System.out.println(message);
            return true;
        } return false;
    }
    

    }

    Beautiful!

    The only way to improve it would be to use an annotated IoC framework to inject an enterprise output writer factory to obtain an appropriate Writer object rather than assuming that stdout is appropriate.



  • @Xyro said:

    Beautiful!
     

    AWESUM



  •  @blakeyrat said:

    @toth said:
    @blakeyrat said:
    @Faxmachinen said:
    That's a good example of how not to use the ternary operator. Some comments help clear things up, but I'd still not recommend it.

    Maybe next time define the word you pulled out of your ass before using it, and I won't make fun of you with clamp clip art. Just FYI.

    Wait, really? There are computer scientists (software developers, whatever) who don't know of the term "clamp" in the sense of "coercing a value to a certain range"?

    It must be a regional thing. I've never heard that before in my life. And it's also stupid, considering how an actual clamp works... although I suppose the geeks who use the word "clamp" that way have never actually used a clamp.

    In any case, that definition isn't in the dictionary, so you can't blame me for not knowing it.

    [quote user="http://en.wiktionary.org/wiki/clamp"] 

    Verb

    clamp (third-person singular simple present clamps, present participle clamping, simple past and past participle clamped)

    1. (transitive, intransitive) To fasten in place or together with (or as if with) a clamp.
      • 1897, Bram Stoker, Dracula Chapter 21
        As we burst into the room, the Count turned his face, and the hellish look that I had heard described seemed to leap into it. His eyes flamed red with devilish passion. The great nostrils of the white aquiline nose opened wide and quivered at the edge, and the white sharp teeth, behind the full lips of the blood dripping mouth, clamped together like those of a wild beast.
    2. (transitive) To hold or grip tightly.
    3. (transitive) To modify a numeric value so it lies within a specific range.

    [/quote][quote user="http://www.google.com/dictionary?langpair=en%7Cen&q=clamp&hl=en"]

    • clamp Noun   /klamp/
      Synonyms:
      • clamps plural
      • A brace, band, or clasp used for strengthening or holding things together
      • An electric circuit that serves to maintain the voltage limits of a signal at prescribed levels
    • clamp Verb   /klamp/
      • clamps 3rd person singular present;   clamping present participle;   clamped past tense;   clamped past participle
      • Fasten (something) in place with a clamp
        • the sander is clamped onto the edge of a workbench
      • Fasten (two things) firmly together
        • the two frames are clamped together
      • Hold (something) tightly against or in another thing
        • Maggie had to clamp a hand over her mouth to stop herself from laughing
      • Maintain the voltage limits of (an electrical signal) at prescribed values

    [/quote] 

    I've heard the usage a few times, but coming from an electronics and graphics background, I've always used the word "clipping" myself.  If you hear it for the first time as part of the phrase "clamping a value to a range", it's pretty obvious what it has to mean.

     



  • Hmm, that's interesting. I've never heard clip and clamp used as synonyms. I think I'm remembering this right. Clamping was when you, for example, bias an AC signal to a certain minimum DC threshold, and clipping is when you chop off the top of that signal to fit into a absolute-value-maximum DC threshold. Like, with analog TV signals, you had to clamp the frame thingy to whatever the TV's minimum voltage was. Or if you had to rectify an AC waveform to be normalized at ground but fit within +/- 5 volts, you'd clamp its bias to 0 and clip the extremes to within range. Am I thinking about that right? It's been a while since I've messed with that stuff.



  • @Xyro said:

    Am I thinking about that right? It's been a while since I've messed with that stuff.

    Yep, you remembered it right.  I was surprised to find the range-limit-a-voltage definition in google's dictionary too; I'm only familiar with the term "clamp" meaning limit to a range of values being used in a mathematical or programming context.




  • @blakeyrat said:

    The real point is that for() and foreach() are *not* equivalent in the way that if() and ?: are.
     

    But if() and ?: are not equivalent. "condition ? success : failure" is an expression, it has a value. if() is a statement, it has no value.

    You can achieve ?:'s purpose using if(), but that often involves jumping through a couple of hoops. In those cases, IMO, using ?: yields clearer and more maintainable code.

    (Of course, there are languages like Haskell where if then else is an expression and has a value, but those usually don't have ?:.)



  •  

    FizzBuzz

    In terms of elegance and maintainabillity, I like this solution best, even though it makes the least use of language features:

    for (int i = 0; i < 100; i++) {
        boolean fizzOrBuzz = false;
        if (i % 3) {
            print("fizz"); fizzOrBuzz = true;
        }
        if (i % 5) {
            print("buzz"); fizzOrBuzz = true;
        }
        if (!fizzOrBuzz) {
            print(i);
        }
    }

    @Astaedus said:

    Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No, because a good compiler will probably produce the same result for both loops.

    Sure there is. Java:

    public void doStuffForAll(List things) {
        for (int i = 0; i < things.size(); i++) {
            doStuff(things.get(i));
        }
    }

    this works like a charm - as long as your list allows random access. But as soon as someone decides to pass a linked list, your running time explodes. Unfortunately you can't easily detect that if you want to keep things generic. The equivalent for-each version doesn't have this problem - because the list (and not your code) does the actual iterating, each implementation can choose the most efficient way.

    (I think I brought the same example in an earlier thread for a different problem. Apologies if I start repeating myself.)



  • @PSWorx said:

    @Astaedus said:

    Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No, because a good compiler will probably produce the same result for both loops.

    Sure there is. Java:

    public void doStuffForAll(List things) {
        for (int i = 0; i < things.size(); i++) {
            doStuff(things.get(i));
        }
    }

    this works like a charm - as long as your list allows random access. But as soon as someone decides to pass a linked list, your running time explodes. Unfortunately you can't easily detect that if you want to keep things generic. The equivalent for-each version doesn't have this problem - because the list (and not your code) does the actual iterating, each implementation can choose the most efficient way.

     

    Just to play pedantic dickweed devil's advocate...you can pretty easily achieve the same kind of safety in Java using a standard for loop. For instance:

    public void doStuffForAll(List things) {
        for (Iterator i = things.iterator(); i.hasNext();) {
            doStuff(i.next());
        }
    }

    IIRC, this is essentially how Java's foreach loop is implemented under the hood. Does using the foreach loop result in a better software product than this code?



  • @Someone You Know said:

    IIRC, this is essentially how Java's foreach loop is implemented under the hood. Does using the foreach loop result in a better software product than this code?

    (Yes, that is how the foreach is implemented: it just calls an Iterable's .iterator() method and handles the Iterator's next()s itself. If only you could hand it an Iterator, too, but sadly only an Iterator will do. Good old Java, always finishing at 95%...)

    I would argue that yes, using a foreach does result in better software product for the very same reason that sane variable names, standard usage of flow structures, and a resistance of cleverness results in a better software product. for(Thing thing : Iterable<Thing> iterable) is better than for(Iterator<Thing> thingIter = iterable.iterator(); thingIter.hasNext();) because it's easier to type and easier to read. It reduces the mental parsing overhead, and saves a whole line (a whole line!) within the loop where you'd otherwise have to write Thing thing = thingIter.next();. Generally speaking, less code to understand means easier understanding. (Obviously I'm not talking about golfing here, so let's not go there.) (Unless it makes the thread more fun.) Just as in oration, terseness can be either good or bad, but in general, speeches that are short and to the point are easier to digest and more memorable than rambly constructs of over-fluent, over-punctuated, and over-inflated monologues. Such as in enterprisey frameworks.


Log in to reply