• Daniel15 (unregistered)

    I've seen the first one heaps of times, it's not funny...

    Is the comments system broken? Or am I the first to reply? :P

  • Martin (unregistered)

    What is wrong with the StringToLong method?

    The loop just remove all the zeros from the start of the string. (Yes it is a stupid way to do it, but is there something even worse that I am missing?)

  • Daniel15 (unregistered) in reply to Daniel15
    I've seen the first one heaps of times, it's not funny...
    Bah, that came out wrong, I was meant to say something like "I've seen the first one so many times that it's just not funny any more."
  • loldongs (unregistered)

    My mind has been boggled by these loops

  • Bunny (unregistered) in reply to Martin

    Curious, what would be a better way to do it?

  • Bunny (unregistered) in reply to Bunny
    Bunny:
    Curious, what would be a better way to do it?

    Should be in reply to:

    The loop just remove all the zeros from the start of the string. (Yes it is a stupid way to do it, but is there something even worse that I am missing?)

    -Sorry

  • Dave (unregistered)

    I might point out that the first function isn't really doing the same thing as a break statement would. When ( condition ) is true in the original WTF, /* something else important */ still happens, whereas with a break it wouldn't. Now I'm not saying that the snippet is the best way of writing it, but it's not as simple as just "use break, dammit"

  • nobody (unregistered)
          if ( result == null ) return;
              return result;
    

    I don't think this will even compile, as a function either returns something (null OK if it is an object) or doesn't return anything (void return type)

    And I'm not going to waste my time checking this.

    As for the first one, back in the FORTRAN IV days, I had to use tricks like that; I was pleased with more modern languages and the break statement.

    captcha: yummy well, breakfast (eating it while reading wtf) was OK.

  • Richie (unregistered) in reply to Bunny

    long StringToLong( String s ) { for ( int j = 0 ; (j < s.length()) && ( s.chatAt(0) == '0' ); j++ ) { s = s.substring(1);

      }
      return Long.parseLong( s );
    

    }

  • nobody (unregistered) in reply to Dave
    Dave:
    I might point out that the first function isn't really doing the same thing as a break statement would. When ( condition ) is true in the original WTF, /* something else important */ still happens, whereas with a break it wouldn't. Now I'm not saying that the snippet is the best way of writing it, but it's not as simple as just "use break, dammit"

    The break goes after the /* something else important */ And I wonder if that code actually uses the value of i, because it will get 11.

  • (cs) in reply to Bunny
    Curious, what would be a better way to do it?
    How about:
    while(s.length() && s.charAt(0) == '0') s = s.substring(1);
  • NicoTjoooooh (unregistered)

    chatAt ?

    Thats were you get to chat to a string?

  • (cs)

    Better way (for example):

    s = s.replaceAll("^0+",""); // have not tested RegExp

  • (cs)

    That's why I prefer proper {}'s.. Properly {}'ed:

      foreach ( Term t in current ) 
      {
          if ( category == "" )
          {
              result = t;
              break;
          }
          else if ( t.category == category )
          {
             result = t;
          }
      }
      if ( result == null ) 
      {
        return;
      }
      return result;
    

    It's not that bad - without a break it returns the last item found instead of the first.. ;)

    ..And shouldn't that be 'charAt' and not 'chatAt'? ;)

  • TheD (unregistered) in reply to nobody
    nobody:
    Dave:
    I might point out that the first function isn't really doing the same thing as a break statement would. When ( condition ) is true in the original WTF, /* something else important */ still happens, whereas with a break it wouldn't. Now I'm not saying that the snippet is the best way of writing it, but it's not as simple as just "use break, dammit"

    The break goes after the /* something else important */ And I wonder if that code actually uses the value of i, because it will get 11.

    Why would it ever be 11?

  • (cs) in reply to GettinSadda
    GettinSadda:
    Curious, what would be a better way to do it?
    How about:
    while(s.length() && s.charAt(0) == '0') s = s.substring(1);

    What if s = "0"?

    Besides, Long.parseLong is perfectly capable of handling leading 0's on its own.

  • rick (unregistered)

    StringToLong

    1. I had no idea that Long.parseLong() couldn't handle leading zeros (I'm guessing that it can)

    2. I'd feel really nervous about s.length() as a condition in the for loop since we're modifying the length of s inside the loop. This probably only works because there are more non-zero digits than leading zeros (and because the Long.parseLong() handles leading zeros). For instance, an input of '00001' would reduce to '01', not '1'.

    3. What's wrong with a while loop?

    while( s.length()> 0 && s.charAt(0) == '0') s = s.substring(1); return parse.parseLong(s);

  • Spand (unregistered)

    The StringToLong is completely foobar.. Why are they even trying to remove the '0's? Im pretty certain that parseLong will succeed at parsing "0002" and give the same result as with "2".

  • (cs) in reply to rick
    1) I had no idea that Long.parseLong() couldn't handle leading zeros (I'm guessing that it can)

    In Java, JavaScript and others, a leading zero signifies an octal number, just like the prefix "0x" signifies Hex.. Hint: Always specify 10 as the radix.. ;)

  • LizardKing (unregistered) in reply to Martin
    What is wrong with the StringToLong method?

    The fact that Long.parseLong handles leading zeros:

    public class PL {
        public static void main(String[] args) {
            String s = "00004567";
            System.out.println("String '" + s + "' as a long " + Long.parseLong(s));
        }
    }
    

    No loop necessary, despite the idiotic posts that use charAt and substring (they're WTF material themselves).

  • sys<in (unregistered) in reply to nobody

    What if the spec was "if condition X occurs, set the value of i to 11, do something-else-important, and exit the loop"?

    Another possibility is that the value of I has no bearing in the commented-out parts, but the condition else can only be tested at the point where the if test was inserted.

    Without knowing what the removed parts parts do, there is no way of knowing if that is a WTF or not.

    captcha:ninjas

  • binky (unregistered)

    long StringToLong (string s){ return Long.valueOf(s).longValue(); }

    or

    new Long(Long.parseLong(s)).longValue();

    Which really shouldn't even be a method and just done inline (in Java 1.5 at least).

  • Rich (unregistered) in reply to rick

    In some languages (e.g.: PHP) string-to-long parsing assumes a 'number' with a leading zero to be octal (base-8), in the same way that a 'number' with a leading "0x" is assumed to be hexadecimal (base-16).

    So, "010" would return a decimal value of 8, whereas "10" would return a decimal value of (yes, you guessed it) 10.

    This looks like Java though -- a quick 30 second look at the API shows that Long.parseLong(String s) ALWAYS assumes decimal. There is a separate Long.parseLong(String s, int radix) that lets you explicitly specify the radix if you need to.

    I wonder how many WTFs could be avoided by a quick look at the API... =)

  • (cs)

    Iteration; see loop

    Loop; see Iteration

  • (cs) in reply to Trondster
    Trondster:
    In Java, JavaScript and others, a leading zero signifies an octal number, just like the prefix "0x" signifies Hex.. Hint: Always specify 10 as the radix.. ;)

    Seems my Java is too rusty again.. When parsing, the radix is always 10 by default. However, when specifying literals, like "int foo=010;", you get octal numbers with leading zeros.

    However, when parsing numbers in JavaScript, leading zeros indeed signify octal numbers. That's why many poorly written date selectors fail for august and september..

  • dcmet (unregistered) in reply to Bunny
    Bunny:
    Curious, what would be a better way to do it?
    "0001".TrimStart('0');

    A regex should also do it, but it's extra effort.

  • binky (unregistered) in reply to binky
    binky:
    long StringToLong (string s){ return Long.valueOf(s).longValue(); }

    or

    new Long(Long.parseLong(s)).longValue();

    Which really shouldn't even be a method and just done inline (in Java 1.5 at least).

    Oh yeah, forgot about Octal.

    How about:

    Long.parseLong(s, 10).longValue(); // base 10

  • jrrs (unregistered) in reply to Dave
    I might point out that the first function isn't really doing the same thing as a break statement would. When ( condition ) is true in the original WTF, /* something else important */ still happens, whereas with a break it wouldn't. Now I'm not saying that the snippet is the best way of writing it, but it's not as simple as just "use break, dammit"
    The statement
    if ( condition ) i = 11;
    terminates with a ';' so that /* do something else important */ always gets executed no matter what 'condition' is. Setting i to 11 if 'condition' is true just ensures the loop will terminate (eventually?).
  • Ohnonymous (unregistered)

    The real WTF is that StringToLong doesn't look for a leading "-" even though it returns a signed value.

  • Hux (unregistered) in reply to rmr
    rmr:
    Besides, Long.parseLong is perfectly capable of handling leading 0's on its own.

    I don't know this for a fact or anything, but does Long.parseLong cause the function to interpret strings with leading zeroes as octal?

  • poo (unregistered) in reply to ParkinT
    ParkinT:
    Iteration; see loop

    Loop; see Iteration

    Recursion; see recursion

  • Rich (unregistered) in reply to Hux

    No, in Java it's always base-10.

    Please iterate over the earlier posts once again... =)

  • tchize (unregistered) in reply to Martin
    Martin:
    What is wrong with the StringToLong method?

    The loop just remove all the zeros from the start of the string. (Yes it is a stupid way to do it, but is there something even worse that I am missing?)

    Yes, the loop does not remove all '0' but instead does remove s.length()/2 rounded up leading zeros.

    let it be s="00005" j=0, s="00005", s.length()=5 j=1, s="0005", s.length()=4 j=2, s="005", s.length()=3 j=3, s="05", s.length()=2 3 > 2 , end of loop

    call is then done to Long.parseLong("05");

    :D

  • Robert Watkins (unregistered) in reply to Trondster

    [quote]In Java, JavaScript and others, a leading zero signifies an octal number[quote]

    long foo = 00020; // octal long bar = Long.parse("00020"); // decimal

    assert foo = 16; assert bar = 20;

    Long.parse() assumes a radix of 10 if you don't specify - see the Javadoc.

  • Shareware (unregistered) in reply to Rich

    Perl always win.

    #lame code ahead

    @twosomething = (1..255);

    foreach $ip (@twosomething) { pring 192.168.0.$ip; }

    that way you can have a "named section"

    @salesIps = (13..98);

    foreach $ip (@salesIP) { callShutdown($ip); }

    Thats much better than this one (c-ish):

    for($t=$minimalSalesIp;$t<=$maxSalesIp;$t++){ callShutdown($t); }

    People whine that Perl is unreadable, but tome can be even more readable than everything else If you try to.

    Of course, thinks like Ruby can add something to this...

    #Fake Ruby code ahead

    salesIp.each {|ip| callShutdown(ip) };

    Still.. I think the Perl way is more readable for most people, acustomed to the C way object-less, or acustomed to the poor objectability of Java.

  • (cs)

    My last job forbade the use of breaks in anything but a switch/case statement.

  • RobertB (unregistered) in reply to ParkinT
    ParkinT:
    Iteration; see loop

    Loop; see Iteration

    Dammit, now I've got to wait for a stack overflow before I can read the rest of the posts.

    captcha: digdug -- an inferior clone of Mr. Do!

  • Foo (unregistered) in reply to Bunny
    Bunny:
    Bunny:
    Curious, what would be a better way to do it?

    Should be in reply to:

    The loop just remove all the zeros from the start of the string. (Yes it is a stupid way to do it, but is there something even worse that I am missing?)

    -Sorry

    Strings in Java are immutable, so every time s = s.substring(1) is called it is creating a brand new string and copying the substring into that new string. If this utility code is running on the server and it's in a high volume application that's a lot of extra load on the garbage collector.

    IIRC, also Long.parseLong(s) strips leading zeros. Even if it doesn't, there are far more efficient ways of doing this like scanning through the string looking for the first non-zero character.

  • El Quberto (unregistered) in reply to TheD
    TheD:
    Why would it ever be 11?

    If you incremented "i" inside of the loop. I could see that in something like this:

    for (int i = 0; i < myString.length-1; i++) { if (myString.substring(i,i+1).equals("A")) { i++; continue; } // blah }

    Note: I didn't say it was a good practice

  • (cs) in reply to Dave
    Dave:
    I might point out that the first function isn't really doing the same thing as a break statement would. When ( condition ) is true in the original WTF, /* something else important */ still happens, whereas with a break it wouldn't. Now I'm not saying that the snippet is the best way of writing it, but it's not as simple as just "use break, dammit"
    Uh yeah it is, it's just that the break goes after the other important thing...
    Martin:
    What is wrong with the StringToLong method?

    The loop just remove all the zeros from the start of the string. (Yes it is a stupid way to do it, but is there something even worse that I am missing?)

    Well the fact that parseLong works without having to strip the leading 0s sure makes me wonder why the hell you'd bother stripping them manually.
    Richie:
    long StringToLong( String s ) { for ( int j = 0 ; (j < s.length()) && ( s.chatAt(0) == '0' ); j++ ) { s = s.substring(1);
      }
      return Long.parseLong( s );
    

    }

    GettinSadda:
    Curious, what would be a better way to do it?
    How about:
    while(s.length() && s.charAt(0) == '0') s = s.substring(1);
    shoko:
    Better way (for example):

    s = s.replaceAll("^0+",""); // have not tested RegExp

    Dudes, how about just using

    long StringToLong(String s) {
        return Long.parseLong(s);
    }

    Cause it sure seems to work on my machine...

    Trondster:
    1) I had no idea that Long.parseLong() couldn't handle leading zeros (I'm guessing that it can)

    In Java, JavaScript and others, a leading zero signifies an octal number, just like the prefix "0x" signifies Hex.. Hint: Always specify 10 as the radix.. ;)

    Not in Java, or at least not for parseLong: if you don't give a radix, parseLong defauts to base 10, not to the language's parsing of literals, as mentioned in the Javadoc:

    Parses the string argument as a signed decimal long. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' (\u002D') to indicate a negative value. The resulting long value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseLong(java.lang.String, int) method.
    binky:
    binky:
    long StringToLong (string s){ return Long.valueOf(s).longValue(); }

    or

    new Long(Long.parseLong(s)).longValue();

    Which really shouldn't even be a method and just done inline (in Java 1.5 at least).

    Oh yeah, forgot about Octal.

    How about:

    Long.parseLong(s, 10).longValue(); // base 10

    Dude, your code's a trainwreck, Long.parseLong returns a long not a Long, and it defaults to base 10 when no radix is given...

    Hux:
    rmr:
    Besides, Long.parseLong is perfectly capable of handling leading 0's on its own.

    I don't know this for a fact or anything, but does Long.parseLong cause the function to interpret strings with leading zeroes as octal?

    No it doesn't, go read the damn javadoc already, please.
  • maht (unregistered) in reply to Shareware

    Kiss the snake

    [call_shutdown(ip) for ip in sales_ips]

  • (cs)

    endless...

  • Sick Boy (unregistered) in reply to lyates

    I think everyone's forgeting that the best way to solve any problem is a case statement.

    int j = 0;

    while(s.CharAt(j) == '0') j++;

    switch(j) { case 1: s=s.substring(1);break; case 2: s=s.substring(2);break; case 3: s=s.substring(3);break; case 4: s=s.substring(4);braek; etc... }

    return Long.parseLong(s);

  • Sean (unregistered) in reply to Foo
    Foo:
    Strings in Java are immutable, so every time s = s.substring(1) is called it is creating a brand new string and copying the substring into that new string. If this utility code is running on the server and it's in a high volume application that's a lot of extra load on the garbage collector.

    Not exactly. String.substring() uses a package level constructor on the String class that allows a substring to share the data of its parent string. It does not need to copy the data each time because it knows that the object it is passing the data array to is another immutable string. Anyway, that doesn't make the code any less of a wtf since Long.parseLong() could have been used on the string with leading zeroes.

  • (cs) in reply to Spand
    The StringToLong is completely foobar..
    'foobar' as in F*cked Object-Oriented Beyond All Reason/Recognition ?

    And why does everyone keeps posting the CAPTCHA's? Aren't you guys affraid the Evil Spammers (tm) will make a list and start spamming this forum :)

    -Edoode

  • (cs) in reply to Shareware
    Shareware:
    Perl always win.

    #lame code ahead

    @twosomething = (1..255);

    foreach $ip (@twosomething) { pring 192.168.0.$ip; }

    that way you can have a "named section"

    @salesIps = (13..98);

    foreach $ip (@salesIP) { callShutdown($ip); }

    Thats much better than this one (c-ish):

    for($t=$minimalSalesIp;$t<=$maxSalesIp;$t++){ callShutdown($t); }

    People whine that Perl is unreadable, but tome can be even more readable than everything else If you try to.

    Of course, thinks like Ruby can add something to this...

    #Fake Ruby code ahead

    salesIp.each {|ip| callShutdown(ip) };

    Still.. I think the Perl way is more readable for most people, acustomed to the C way object-less, or acustomed to the poor objectability of Java.

    I think I might be part of the problem then. If these loops weren't likely to be expanded on, I'd write them as:

    my @twosomething = (1.255); my @salesIps = (13..98);

    ping 129.168.0.$_ for @twosomething; callShutdown($_) for @salesIps;

    Perl most certainly, doesn't always win though, lets return a reference to a array of upper cased entries in the name column of a database table passed as the only argument.

    sub returnUpperCaseNames {
     return [map {uc($_->[0])} @{DB->exec('SELECT name FROM $_[0]')}];
    }
    
  • Zman (unregistered)

    Snakelin, I am with ya all the way. Half the comments were a WTF in and of themselves.

  • Svend Karlson (unregistered)

    Manager: Why set it to 11? Coder: Well, it would be one better then, wouldn't it?

  • waefafw (unregistered)

    Bad programmers makes baby Jesus cry.

  • Ilya Martynov (unregistered)

    This topic reminded me a bit of code my co-worked showed me last week. It looked like:

    my @list = ();
    for my $elem (@list) {
        # nearly a page of code here
        ...
        ...
    }
    

Leave a comment on “Breaking Out of the Box”

Log In or post as a guest

Replying to comment #:

« Return to Article