SingleQautedString(), RemoveMeFunction(), Human-Friendly Dates, and More

« Return to Article
  • ParkinT 2011-09-26 08:03
    "SpTCRUtl_showNumTelHL7" is my favorite password!!
    How did he know that? Big Brother is watching me...
  • Space Time Continuum 2011-09-26 09:04
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);
  • BlackBart 2011-09-26 09:05
    I'm going to wear my Ghostbusters gb_custome for Halloween.
  • mott555 2011-09-26 09:09
    Adam's date code was so efficient Alex had to include it twice!
  • m 2011-09-26 09:10
    Space Time Continuum:
    "While looking through some old code, I found this snippet …

    Please post this one again as penultimate comment.
  • MacHaggis 2011-09-26 09:14
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."
    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);
  • my fault? 2011-09-26 09:17
    The one by Andrew seems awfully familiar...
  • Stev 2011-09-26 09:18
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);
  • gobes 2011-09-26 09:23
    Stev:
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);

    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."
    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);
  • eVil 2011-09-26 09:30
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?
  • WC 2011-09-26 09:32
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Thanks. I was starting to doubt my sanity on that one because I could not imagine the ugly if statement required to validate that in the same way.
  • eVil 2011-09-26 09:34
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Although, there should probably be a check on the 2nd and third repetitions, to check whether the previous instances of that loop actually find something (currently, if the first loop finds what its looking for, it breaks the loop nicely, then somewhat stupidly enters an almost identical loop to look for something it has already found)... those checks would actually add another 2 if statements.
  • pjt33 2011-09-26 09:38
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?

    Efficient? Using a loop through a contiguous range of values to check whether a value is in that range?
  • MoreEfficient 2011-09-26 09:41
    gobes:
    Stev:
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);

    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."
    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);



    Perhaps this is more efficient than just posting it once.
  • Severity One 2011-09-26 09:42
    eVil:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?
    Although, there should probably be a check on the 2nd and third repetitions, to check whether the previous instances of that loop actually find something (currently, if the first loop finds what its looking for, it breaks the loop nicely, then somewhat stupidly enters an almost identical loop to look for something it has already found)... those checks would actually add another 2 if statements.
    You are joking, right? Adding Boolean algebra is inglorious?

    Well, we're talking about VBScript, so it's inglorious by definition, I'll give you that.
  • eVil 2011-09-26 09:42
    pjt33:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?

    Efficient? Using a loop through a contiguous range of values to check whether a value is in that range?


    Not knowing exactly which language that was, I just assumed that cint() was some kind of array of values being indexed into... is this not the case?
  • x 2011-09-26 09:43
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Not sure about my VB syntax, but why not this :

    bolMatch=(cint(val) >= 3000 and cint(val) <= 3299) or (cint(val) >= 3351 and cint(val) <= 3441) or (cint(val) >= 5964 and cint(val) <= 5969)

    or that ?

    if cint(val) >= 3000 and cint(val) <= 3299 then bolMatch=true
    else if cint(val) >= 3351 and cint(val) <= 3441 then bolMatch=true
    else if cint(val) >= 5964 and cint(val) <= 5969 then bolMatch=true
  • The poop... of DOOM! 2011-09-26 09:43
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?

    My main point of pain in that one, is why it has to do so many iterations? That takes time! You can cut each for away and add an extra condition (or two, depending on what the language provides) to the existing IF statement. You can actually combine all three such IF statements into one, but that would indeed cost in maintainability.

    Additionally, I've always been taught that breaking out of a for-loop is bad practice. Logically speaking, if your loop should end on a certain condition being met instead of running through all defined iterations, you'd need to use a while loop (either a while do or a do while, depending on) and not a for loop.

    Also, frist!
  • eVil 2011-09-26 09:44
    Seeing now that that isn't some kind of index, I now feel sick.

    God almighty.
  • none 2011-09-26 09:48
    Yes, given VB's lovely syntax, it _could_ be. However, C${TYPE} functions are used for conversion, so this probably means:
    if ((int)val == (int)i);

    Even though I actually often work with VBScript, I missed that too... Brain trying to escape the horror, I guess ;).
  • eVil 2011-09-26 09:51
    Plus its fine to break out of a for loop, so long as its obvious why you're breaking, and the loop isn't horrendously complicated.

    People just *think* that its bad practice, because it similar to using 'goto's in a way... however it is a very specific form of goto.... eg one that doesn't cause a spaghetti-code problem.
  • My Name Is Missing 2011-09-26 09:51
    A human friendly duplication of WTFs?
  • frits 2011-09-26 09:54
    "I found this code at the day job (a large bank)," notes Dave, "maybe it's just me, but I would think a single 'if' statement could have done the job."

    You don't even need an 'if' statement...

    bolMatch =
    (Enumerable.Range(3000, 300).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(3351, 91).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(5964, 6).Where(Function(x) x = val).Count() > 0)

  • BlueCollarAstronaut 2011-09-26 10:00
    This one was pretty awesome:
    // ATTENTION: IF SOMEONE READS BLOCKS OF CODE ABOVE AND BELOW
    // THIS LINE - PLEASE DONT TRY TO UNDERSTAND IT - I DON'T

    There are places I may need to borrow that comment.

    I'm a bit disappointed, though, because I thought Adam Smith's human-friendly date formatter WTF was going to be in today's article. Maybe next week...
  • justsomedude 2011-09-26 10:01
    Best WTF post I've seen in here in some time.
  • SCSimmons 2011-09-26 10:02
    "A lot of students only go to school three quarters a year," Bob writes, "so maybe the author thought a business might take a summer off. Or try to squeeze another one in."

    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }

    Am I missing something? This seems to me to return a four-element array of strings, getQuarters(0) is "1", (1) is "2", (2) is "3", and (3) is "4"; it may be confusing and ugly, but still should work & not leave out any quarters ... Mostly just an illustration of why not to be rigid about your indexing standards.

    I'd compile it and verify, but I have a long-standing policy of not copying any code from this site for any purpose.
  • Sir Twist 2011-09-26 10:12
    This is due to the “no magic numbers” requirement being enforced to idiotic levels. Ludicrous levels would require the additional constants LOOP_START_ZERO = 0 and NEXT_INTEGER = 1, and prohibit the use of “++” and “--” operators, because 1 is also a magic number.
  • ac 2011-09-26 10:13
    eVil:
    Plus its fine to break out of a for loop, so long as its obvious why you're breaking, and the loop isn't horrendously complicated.

    People just *think* that its bad practice, because it similar to using 'goto's in a way... however it is a very specific form of goto.... eg one that doesn't cause a spaghetti-code problem.


    Just like "goto", the "break" keyword does not cause spaghetti-code problems. The problem is that people use it in spaghetti logic which causes spaghetti-code problems.

    Consider Windows SDK C++ examples for SSL negotiation, which involves repeatedly invoking the same function (InitializeSecurityContext() on the client and AcceptSecurityContext() on the server) at different steps of the negotiation process. The thing is, each set requires a different combinations of parameters and have different effects, different error codes, etc.

    For some reason, the developer who wrote the example noticed the process involves almost exclusively calls to the same function and thought it was a good idea to make one big loop out of this. The mess is full of "break" and "continue" statements. All structured programming. All-star spaghetti.
  • Danimal 2011-09-26 10:14
    "A lot of students only go to school three quarters a year," Bob writes, "so maybe the author thought a business might take a summer off. Or try to squeeze another one in."

    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }


    The REAL WTF is that there are always 4 quarters in a year. There could be 3 trimesters, though.
  • PleegWat 2011-09-26 10:14
    I've got one colleague who tends to write things like #define N_HR 24. I've got another who tends to sprinkle magic numbers like 86400 (seconds per day) all over the place. Guess what I prefer maintaining...
  • eVil 2011-09-26 10:16
    Why not just

    const string[] Quarters = {"1","2","3","4"}

    The coder already knows that the number of quarters in a year is constant, so it's surprising he doesn't know that the actual quarters themselves also don't change!
  • ac 2011-09-26 10:16
    SCSimmons:
    Am I missing something? This seems to me to return a four-element array of strings, getQuarters(0) is "1", (1) is "2", (2) is "3", and (3) is "4"; it may be confusing and ugly, but still should work & not leave out any quarters ...


    Think of why this function exists. Someone probably thought that:


    String[] quarters = getQuarters();
    for ( ... ) {
    }


    was [i]a possible customization point[i] not provided by duplication of statements such as:


    String[] quarters = new String[]{"1", "2", "3", "4"};
    for ( ... ) {
    }
  • The poop... of DOOM! 2011-09-26 10:21
    PleegWat:
    I've got one colleague who tends to write things like #define N_HR 24. I've got another who tends to sprinkle magic numbers like 86400 (seconds per day) all over the place. Guess what I prefer maintaining...

    I've maintained code where they put everything in #defines so as to avoid magic numbers... except for a few numbers. Go debug then! They've also added typos in the defined names, or have given it names harder to understand than N_HR. I've learned alot about magic numbers from that, namely that setting the defines should be done with care and thought.

    I myself, when writing code, only make defines when the number is indeed fixed and appears in several parts of the code. Otherwise, if it's just in one function, I'll go with what your 2nd colleague does, but add a comment, saying what the number means.
  • 1000 monkeys 2011-09-26 10:36
    frits:
    "I found this code at the day job (a large bank)," notes Dave, "maybe it's just me, but I would think a single 'if' statement could have done the job."

    You don't even need an 'if' statement...

    bolMatch =
    (Enumerable.Range(3000, 300).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(3351, 91).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(5964, 6).Where(Function(x) x = val).Count() > 0)



    fixed?

    if cint(val)=cint(3000) then
    bolMatch=true
    end if
    if cint(val)=cint(3001) then
    bolMatch=true
    end if
    if cint(val)=cint(3002) then
    bolMatch=true
    end if
    if cint(val)=cint(3003) then
    bolMatch=true
    end if
    if cint(val)=cint(3004) then
    bolMatch=true
    end if
    if cint(val)=cint(3005) then
    bolMatch=true
    end if
    if cint(val)=cint(3006) then
    bolMatch=true
    end if
    ...



  • Rajeesh! 2011-09-26 10:39
    The problem SingleQautedString has not found by American colleagues? What if String already contains single Quat? It needs exkaped.

    Also name too long. For double quating just call Dquat and of courst this function Squat. I expert write Squat code all day.
  • Deja Vu 2011-09-26 10:40
    Ok, got a new one for you:

    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);
  • 10000 monkeys 2011-09-26 10:44
    1000 monkeys:


    ...


    fixed?

    if cint(val)=cint(3000) then
    bolMatch=true
    end if
    if cint(val)=cint(3001) then
    bolMatch=true
    end if
    if cint(val)=cint(3002) then
    bolMatch=true
    end if
    if cint(val)=cint(3003) then
    bolMatch=true
    end if
    if cint(val)=cint(3004) then
    bolMatch=true
    end if
    if cint(val)=cint(3005) then
    bolMatch=true
    end if
    if cint(val)=cint(3006) then
    bolMatch=true
    end if
    ...


    mm..surely we would need control over the specific numbers...

    how about:
     
    
    int[] validNumbers = new int[] {3000,3001,3001,3002....}

    for (int i=0; i<validNumbers.Length; i++)
    if (validNumbers[i]==i)
    {
    bolMatch=true;
    break;
    }

  • Carl 2011-09-26 10:45
    create procedure dbo.SpTCRUtl_showNumTelHL7
    
    @numTelIn varchar(50),
    @numTelOut varchar(50) output
    as

    set @numTelOut = @numTelIn
    C'mon, you can find stuff like this in abundance any time you look at machine generated code. It's an empty template that in this instance effectively does nothing. But what the complainer didn't show you is that there's two thousand others like this, one for each data element. Many of them contain logic to manipulate the data; let's say date formatting for example. If one particular element doesn't need any formatting, you just pass it back out as it came in. Not a WTF.
  • Lockwood 2011-09-26 10:46
    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }

    V1 had a spelling error, V1.1 fixed that but needed to keep compatibility with the widely deployed V1?
  • Ahem... 2011-09-26 10:48
    Not only are there always four quarters in a year, there are also always four quarters in a dollar, four quarters in an apple... I think the brighter ones among us can see where I'm going with this...
    const QUARTERS = 4;
    Done!
  • Tracy 2011-09-26 10:54
    For the QUARTERS_IN_A_YEAR, I worked at a company that decided to switch from starting the fiscal year in October to starting it in January. That meant some contortions, making one year have 3 quarters and the next one 5. It was a one time thing but the financial software had to deal with it.
  • PedanticCurmudgeon 2011-09-26 10:55
    Rajeesh!:
    The problem SingleQautedString has not found by American colleagues? What if String already contains single Quat? It needs exkaped.

    Also name too long. For double quating just call Dquat and of courst this function Squat. I expert write Squat code all day.
    I see what you did there.
  • Loren Pechtel 2011-09-26 10:55
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Agreed. The only sane refactor I see is extracting the repeated loop to another routine.

    pjt33:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?

    Efficient? Using a loop through a contiguous range of values to check whether a value is in that range?


    Obviously the code is only supposed to check the specified ranges, not all numbers in between.

    x:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Not sure about my VB syntax, but why not this :

    bolMatch=(cint(val) >= 3000 and cint(val) <= 3299) or (cint(val) >= 3351 and cint(val) <= 3441) or (cint(val) >= 5964 and cint(val) <= 5969)

    or that ?

    if cint(val) >= 3000 and cint(val) <= 3299 then bolMatch=true
    else if cint(val) >= 3351 and cint(val) <= 3441 then bolMatch=true
    else if cint(val) >= 5964 and cint(val) <= 5969 then bolMatch=true


    Sorry, but you're looping through 3000 elements wastefully. Either leave it alone or refactor out the inner loop, don't loop across the whole space and reject the ones you don't want!

  • da Doctah 2011-09-26 11:03
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);


    TRWTF is day-first dates.
  • Macho 2011-09-26 11:03
    When I look into snipped Adam Smith sent, all I see is

    (.) (.)

  • dkf 2011-09-26 11:06
    ac:
    All-star spaghetti.
    Some people write old-school FORTRAN in any language. Some people should be taken out back and put out of our misery. There is an overlap.
  • Rodnas 2011-09-26 11:07
    // ATTENTION: IF SOMEONE READS BLOCKS OF COMMENTS ABOVE AND BELOW
    // THIS COMMENT - PLEASE DONT TRY TO UNDERSTAND IT - I DON'T

  • gallier2 2011-09-26 11:08
    WC:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Thanks. I was starting to doubt my sanity on that one because I could not imagine the ugly if statement required to validate that in the same way.


    As always the RWTF are the comments.

    integer ival = cint(val)
    bolMatch = (ival >= 3000 and ival <= 3299) or
    (ival >= 3351 and ival <= 3441) or
    (ival >= 5964 and ival <= 5969)

    In the worst case the original does:
    394 loop (compare+increment) + 394 comparisons + 2*394 int conversions.
    In the best case it does:
    96 loop (compare+increment) + 96 comparisons + 2*96 int conversions. (if it finds the value in the first loop, the other loops are executed).

    My implementation has in the best case 2 comparisons + 1 conversion in the best case (if that unrecognized language has short cut evaluation) and at most 6 comparisons and 1 conversion.

  • Matt Westwood 2011-09-26 11:12
    Bob:
    "A lot of students only go to school three quarters a year,"

    That's because their ******* retarded.
  • RBeenen 2011-09-26 11:21
    At least they didn't use month-first dates. Those are the worst kind.
  • frits 2011-09-26 11:21
    gallier2:
    WC:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Thanks. I was starting to doubt my sanity on that one because I could not imagine the ugly if statement required to validate that in the same way.


    As always the RWTF are the comments.

    integer ival = cint(val)
    bolMatch = (ival >= 3000 and ival <= 3299) or
    (ival >= 3351 and ival <= 3441) or
    (ival >= 5964 and ival <= 5969)

    In the worst case the original does:
    394 loop (compare+increment) + 394 comparisons + 2*394 int conversions.
    In the best case it does:
    96 loop (compare+increment) + 96 comparisons + 2*96 int conversions. (if it finds the value in the first loop, the other loops are executed).

    My implementation has in the best case 2 comparisons + 1 conversion in the best case (if that unrecognized language has short cut evaluation) and at most 6 comparisons and 1 conversion.


    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.
  • Some damn Yank 2011-09-26 11:31
    Tracy:
    For the QUARTERS_IN_A_YEAR, I worked at a company that decided to switch from starting the fiscal year in October to starting it in January. That meant some contortions, making one year have 3 quarters and the next one 5. It was a one time thing but the financial software had to deal with it.
    Why did the first year have 3 quarters? Wasn't it Oct-Sept as before, and the next year was 5 quarters, Oct to the following Dec, followed by 4 quarters Jan-Dec?

    CAPTCHA: venio. I need to drink some venio after that!
  • gallier2 2011-09-26 11:37
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
  • me 2011-09-26 11:41
    Produce is chicken wing. With wing bark. No Qautk.
  • frits 2011-09-26 11:49
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.

    That's not very polite.
    Do you think we don't know how to check if a number is in a range? We do. Probably every one of us. Even the dumb ones.
  • Little Green Men 2011-09-26 11:50
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.

    Careful. There was a Nagesh on here a while back, and I think he died from doing something very similar.
  • Ken Jennings 2011-09-26 11:52
    I'll take "Non-Subtle Attempts to Start a Flamewar" for 100, Alex.
  • Helena Handcart 2011-09-26 11:53
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.


    It looks like gallier2 wrote the original code, and feels guilty for it. To make amends he's posted a super-efficient rewrite in the hope of saving his soul. He's bound to get shirty if you go and pooh-pooh his considerable efforts. I for one will be implementing his visionary rewrite just as soon as I can.

    Now, where's the upvote button?
  • D-Coder 2011-09-26 11:55
    Danimal:
    "A lot of students only go to school three quarters a year," Bob writes, "so maybe the author thought a business might take a summer off. Or try to squeeze another one in."

    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }


    The REAL WTF is that there are always 4 quarters in a year. There could be 3 trimesters, though.
    I'm voting this one the least WTF-y of the bunch. QUARTERS_IN_A_YEAR explains exactly why this number is here. Words are more explanatory than numbers in almost all cases.

    A word is worth 1,000 numbers.
  • RRDY 2011-09-26 12:03
    ac:
    eVil:
    Plus its fine to break out of a for loop, so long as its obvious why you're breaking, and the loop isn't horrendously complicated.

    People just *think* that its bad practice, because it similar to using 'goto's in a way... however it is a very specific form of goto.... eg one that doesn't cause a spaghetti-code problem.


    Just like "goto", the "break" keyword does not cause spaghetti-code problems. The problem is that people use it in spaghetti logic which causes spaghetti-code problems.

    Consider Windows SDK C++ examples for SSL negotiation, which involves repeatedly invoking the same function (InitializeSecurityContext() on the client and AcceptSecurityContext() on the server) at different steps of the negotiation process. The thing is, each set requires a different combinations of parameters and have different effects, different error codes, etc.

    For some reason, the developer who wrote the example noticed the process involves almost exclusively calls to the same function and thought it was a good idea to make one big loop out of this. The mess is full of "break" and "continue" statements. All structured programming. All-star spaghetti.


    Sounds like a state machine is in order here, which could indeed be implemented as a loop, minus the spaghetti.

    CAPTCHA: nobis (we're all in this together I guess)
  • Vladimir Poutines 2011-09-26 12:06
    I we tall did:

    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.

    As far as I can tell, that seems to be every user's job around here.
  • dgvid 2011-09-26 12:06
    D-Coder:
    ... Words are more explanatory than numbers in almost all cases.

    A word is worth one-thousand numbers.


    FTFY
  • gallier2 2011-09-26 12:12
    frits:

    That's not very polite.
    Do you think we don't know how to check if a number is in a range? We do. Probably every one of us. Even the dumb ones.


    You think you were polite?
    And did you follow the quotes in my post? There seem to be people who think that the original code was not that bad. May be they were joking, but having followed comments here for several years now, there's no doubt that there are people dense enough, to not get why the original code was a WTF.
    Furthermore, some people prefer comments with content. 'frist', "wooden table" and "bobby tables" comments have been boring since their first time they were posted.
  • blah 2011-09-26 12:12
    preg_replace huh. Another Alex FAIL.
  • SCSimmons 2011-09-26 12:16
    ac:
    SCSimmons:
    Am I missing something? This seems to me to return a four-element array of strings, getQuarters(0) is "1", (1) is "2", (2) is "3", and (3) is "4"; it may be confusing and ugly, but still should work & not leave out any quarters ...


    Think of why this function exists. Someone probably thought that:


    String[] quarters = getQuarters();
    for ( ... ) {
    }


    was [i]a possible customization point[i] not provided by duplication of statements such as:


    String[] quarters = new String[]{"1", "2", "3", "4"};
    for ( ... ) {
    }

    Well, yes. But if you do it that way, then if the calendar gets changed and the number of quarters in a year becomes three or five, you've got to make updates all through your code. Having a single public constant that's used to build your arrays lets you make a change in just one spot that can break all of your code at once.
  • frits 2011-09-26 12:22
    gallier2:
    frits:

    That's not very polite.
    Do you think we don't know how to check if a number is in a range? We do. Probably every one of us. Even the dumb ones.


    There seem to be people who think that the original code was not that bad. May be they were joking, but having followed comments here for several years now, there's no doubt that there are people dense enough, to not get why the original code was a WTF.

    Well it certainly is fortuitous that the same types of people who produce such crappy code just happen to read this site.
  • eVil 2011-09-26 12:24
    gallier2:
    frits:

    That's not very polite.
    Do you think we don't know how to check if a number is in a range? We do. Probably every one of us. Even the dumb ones.


    You think you were polite?
    And did you follow the quotes in my post? There seem to be people who think that the original code was not that bad. May be they were joking, but having followed comments here for several years now, there's no doubt that there are people dense enough, to not get why the original code was a WTF.
    Furthermore, some people prefer comments with content. 'frist', "wooden table" and "bobby tables" comments have been boring since their first time they were posted.


    Maybe you ought to read the comments more thoroughly, and read further down, where people have asked questions, discussed answers, and corrected themselves.

    Just because someone is incorrect does not make them dumb... Generally it means they are not in possession of all the facts and have made some reasonable but incorrect assumptions to fill the gaps.

    Then again. maybe you ought to just WTF off!
  • Mez 2011-09-26 12:25
    Adam Smith?? using Regex's to do anything and everything.

    Why do I have a feeling this came from our company? :(

    (Captcha: nulla - a function to set something NULL)
  • Dave-Sir 2011-09-26 12:31
    BlueCollarAstronaut:
    This one was pretty awesome:
    // ATTENTION: IF SOMEONE READS BLOCKS OF CODE ABOVE AND BELOW
    // THIS LINE - PLEASE DONT TRY TO UNDERSTAND IT - I DON'T

    There are places I may need to borrow that comment.


    At a PPOE, I found some code with the folling comment in the header:

    // Here be dragons!

  • Rfoxmich 2011-09-26 12:39
    /**
    * @param str The string which must put into 2 Signle Quat
    * @return The single quated String
    */
    public String SingleQautedString(String str) {
    return "'" + str + "'";
    }


    TRWTF is that if str has embedded quats then you need to excap it with something like a backslush...and deal with exapping backslushes in the string as well... single-quating isn't so easy.
  • gallier2 2011-09-26 12:43
    eVil:

    Maybe you ought to read the comments more thoroughly, and read further down, where people have asked questions, discussed answers, and corrected themselves.


    I don't see why my original comment was not contributing towards that goal. It was not condescending and it contributed to the subject. That other comments were posted, that basically stated the same as mine, during the time I wrote it (I was interrupted while composing) is irrelevant (and as frits noticed, we're not on stackoverflow were such thing would have been noticeable).

    eVil:

    Just because someone is incorrect does not make them dumb...


    Just because someone is dumb does not make them (in)correct...


    eVil:

    Generally it means they are not in possession of all the facts and have made some reasonable but incorrect assumptions to fill the gaps.


    Gaps filled with comments like I did.


    eVil:
    Then again. maybe you ought to just WTF off!


    Bye, bye
  • Leo 2011-09-26 12:45
    1000 monkeys:
    frits:
    "I found this code at the day job (a large bank)," notes Dave, "maybe it's just me, but I would think a single 'if' statement could have done the job."

    You don't even need an 'if' statement...

    bolMatch =
    (Enumerable.Range(3000, 300).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(3351, 91).Where(Function(x) x = val).Count() > 0 Or _
    Enumerable.Range(5964, 6).Where(Function(x) x = val).Count() > 0)



    fixed?

    if cint(val)=cint(3000) then
    bolMatch=true
    end if
    if cint(val)=cint(3001) then
    bolMatch=true
    end if
    if cint(val)=cint(3002) then
    bolMatch=true
    end if
    if cint(val)=cint(3003) then
    bolMatch=true
    end if
    if cint(val)=cint(3004) then
    bolMatch=true
    end if
    if cint(val)=cint(3005) then
    bolMatch=true
    end if
    if cint(val)=cint(3006) then
    bolMatch=true
    end if
    ...





    Looks like magic numbers to me.

    #define THREE_THOUSAND 3000
    #define THREE_THOUSAND_AND_ONE 3001
    #define THREE_THOUSAND_AND_TWO 3002
    ...
    #define THREE_THOUSAND_THREE_HUNDRED_AND_FIFTY_ONE 3351

    if cint(val)=cint(THREE_THOUSAND) then
    bolMatch=true
    end if
    if cint(val)=cint(THREE_THOUSAND_AND_ONE) then
    bolMatch=true
    end if
    ...
  • Boobmaster 2011-09-26 12:45
    Macho:
    When I look into snipped Adam Smith sent, all I see is

    (.) (.)



    Boobies!
  • trtrwtf 2011-09-26 12:48
    gallier2:
    Bye, bye


    Quickest meltdown in tdwtf history?
    Guy went to pieces so fast he took out Nagesh with the shrapnel!

    (stolen, yes, but stolen with love)
  • Jay 2011-09-26 13:02
    I don't think the QUARTERS_IN_YEAR is all that dumb.

    Sure,


    String[] quarters=new String[QUARTERS_IN_YEAR]


    probably adds nothing to the comprehensibility of the code over


    String[] quarters=new String[4]


    I'm sure anyone smart enough to understand the code can figure out that 4 is the logical number of quarters and requires no further explanation.

    But what happens when we get a little farther in the code and we come across a statement that reads:


    for (int n=0;n<4;++n)


    Now a reader might well ask, Why 4? What is this counting over? What's magic about 4? But:


    for (int n=0;n<QUARTERS_IN_YEAR;++n)


    makes the intent clear.

    And once we create such a symbolic constant, we ought to use it everywhere. Do we really want to go through the code and say, "Oh, here it's obvious why we're using 4 so I'll hard-code the number, but over here it's ambiguous, so I'll use the symbolic constant. And this one, hmm, that's debateable, I'd better take a survey of all the programmers in the department and see how many understand the intent if I hard-code the constant." That would be a massive waste of thinking time. Once you've created the constant, just use it.

    The above is doubly true for constants that might change. In the case of quarters, okay, it's not likely that we'll have a calendar reform and start having 5 quarters in a year. (Though another poster did bring up a case where he in fact had to deal with 3 quarters in a year.) But if it's something like, say, number of regions, if some places that's hard-coded and some place we use a symbol, and then we change the number of regions, someone could easily be fooled into thinking that changing the constant solves the problem.
  • Jay 2011-09-26 13:12
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
  • Jay 2011-09-26 13:15
    frits:
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.

    That's not very polite.
    Do you think we don't know how to check if a number is in a range? We do. Probably every one of us. Even the dumb ones.


    Mommy! Mommy! He started a fight! He hit me back!
  • Abso 2011-09-26 13:18
    Leo:

    #define THREE_THOUSAND 3000
    #define THREE_THOUSAND_ONE 3001
    #define THREE_THOUSAND_TWO 3002
    ...
    #define THREE_THOUSAND_THREE_HUNDRED_FIFTY_ONE 3351

    if cint(val)=cint(THREE_THOUSAND) then
    bolMatch=true
    end if
    if cint(val)=cint(THREE_THOUSAND_ONE) then
    bolMatch=true
    end if
    ...

    FTFY.

    This post has been sponsored by your grade three teacher.
  • trtrwtf 2011-09-26 13:22
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.



    365%52 != 0
    Years aren't composed of weeks - a given date is within week N of a given year, determined by Julian date and your conception of where the week is bounded. If your calendar of the year has a set number of weeks you're doing something wrong.
  • hoodaticus 2011-09-26 13:23
    eVil:
    pjt33:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?

    Efficient? Using a loop through a contiguous range of values to check whether a value is in that range?


    Not knowing exactly which language that was, I just assumed that cint() was some kind of array of values being indexed into... is this not the case?
    YOU WISH! It's a fucking cast to int. God I hate VB.
  • Jerry 2011-09-26 13:26
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    Weeks don't fit into months or years, months aren't all the same size, even years have a variable number of days... and don't get me started with hours minutes and seconds that don't multiply by something reasonable but instead by 24 or 60... human time reckoning is a mess!

    What is needed is to replace all time measurements and expressions by a simple integer counter of http://en.wikipedia.org/wiki/Planck_time since the Big Bang.

    OK we might have to show it in hex instead of decimal, so it doesn't take up quite so much room.
  • Iceman 2011-09-26 13:27

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
  • hoodaticus 2011-09-26 13:27
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.
  • hoodaticus 2011-09-26 13:30
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".
  • Al 2011-09-26 13:35
    hoodaticus:
    I like how c is slowing down as magnetic force increases.
    Einstein arbitrarily chose c (in a vacuum) as the only constant. Everything else has to distort to fit. So if light doesn't quite cover 186,000 miles per second any more, it can only mean that the miles have grown longer. Or perhaps seconds are shorter.

    I blame George Bush and Obama. They have not been taking their responsibilities seriously.
  • Brompot 2011-09-26 13:45
    Ahem...:
    Not only are there always four quarters in a year, there are also always four quarters in a dollar, four quarters in an apple... I think the brighter ones among us can see where I'm going with this...
    const QUARTERS = 4;
    Done!


    But there are two quarters in half a dollar and 20 quarters in a fiver.
    40 quarters in a decade and two quarters in a semester.

    You're making the assumption that this is about one whole object (i.e. one whole year). But if you want to change the program to work in semesters...

    It's people like you that keep us programmers working whenever the world changes. Thank you.
  • JamesQMurphy 2011-09-26 13:52
    Ken Jennings:
    I'll take "Non-Subtle Attempts to Start a Flamewar" for 100, Alex.

    I see what you did!
  • silent d 2011-09-26 14:02
    dgvid:
    D-Coder:
    ... Words are more explanatory than numbers in almost all cases.

    A word is worth one-thousand numbers.


    FTFY


    #define NUMBER_OF_NUMBERS_THAT_A_WORD_IS_WORTH 1000
  • the beholder 2011-09-26 14:12
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
    Whoa there. You may feel entitled to post your code correction here and there's nothing wrong with it per se, but there's a side effect you should consider whenever you do that.

    I've seen a few TDWTF articles over the years where someone posts new code to do whatever the article's code was supposed to. Unfortunately the code posted was broken too and in a too obvious way; and then people started posting their (for the most part completely wrong) solutions to a problem they didn't even understand. I think this last one regarded memory management in C, AFAICR.

    There were obvious syntactic and logical errors all around but above all their code didn't even touch the requirements. I stopped reading after I saw that it was the freaking third page and people were still posting flawed code even after someone got it right on the end of first page. It was impossible to find smart comments in the middle of it all.

    I believe frits is trying to discourage this sort of behavior here. It's sort of an unwritten rule, and I support it fully.
  • PedanticCurmudgeon 2011-09-26 14:22
    the beholder:
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
    Whoa there. You may feel entitled to post your code correction here and there's nothing wrong with it per se, but there's a side effect you should consider whenever you do that.

    I've seen a few TDWTF articles over the years where someone posts new code to do whatever the article's code was supposed to. Unfortunately the code posted was broken too and in a too obvious way; and then people started posting their (for the most part completely wrong) solutions to a problem they didn't even understand. I think this last one regarded memory management in C, AFAICR.

    There were obvious syntactic and logical errors all around but above all their code didn't even touch the requirements. I stopped reading after I saw that it was the freaking third page and people were still posting flawed code even after someone got it right on the end of first page. It was impossible to find smart comments in the middle of it all.

    I believe frits is trying to discourage this sort of behavior here. It's sort of an unwritten rule, and I support it fully.
    If you expect to find smart comments here, you've missed frits' point.
  • gallier2 2011-09-26 14:22
    the beholder:
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
    Whoa there. You may feel entitled to post your code correction here and there's nothing wrong with it per se, but there's a side effect you should consider whenever you do that.

    I've seen a few TDWTF articles over the years where someone posts new code to do whatever the article's code was supposed to. Unfortunately the code posted was broken too and in a too obvious way; and then people started posting their (for the most part completely wrong) solutions to a problem they didn't even understand. I think this last one regarded memory management in C, AFAICR.

    There were obvious syntactic and logical errors all around but above all their code didn't even touch the requirements. I stopped reading after I saw that it was the freaking third page and people were still posting flawed code even after someone got it right on the end of first page. It was impossible to find smart comments in the middle of it all.

    I believe frits is trying to discourage this sort of behavior here. It's sort of an unwritten rule, and I support it fully.


    Yeah, well you're a big poopyhead too.
  • JayC 2011-09-26 14:35
    hoodaticus:
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".


    Oh, you mean, like obliterating any trace of monsters such as IE6 from the planet? I'd love to hear your proposals.
  • Matt Westwood 2011-09-26 14:37
    x:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Not sure about my VB syntax, but why not this :

    bolMatch=(cint(val) >= 3000 and cint(val) <= 3299) or (cint(val) >= 3351 and cint(val) <= 3441) or (cint(val) >= 5964 and cint(val) <= 5969)

    or that ?

    if cint(val) >= 3000 and cint(val) <= 3299 then bolMatch=true
    else if cint(val) >= 3351 and cint(val) <= 3441 then bolMatch=true
    else if cint(val) >= 5964 and cint(val) <= 5969 then bolMatch=true


    Yeah, that cint's a cunt, innit
  • gallier2 2011-09-26 14:39
    trtrwtf:
    gallier2:
    Bye, bye


    Quickest meltdown in tdwtf history?
    Guy went to pieces so fast he took out Nagesh with the shrapnel!

    (stolen, yes, but stolen with love)


    That's what you think.
  • trtrwtf 2011-09-26 14:39
    JayC:
    hoodaticus:
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".


    Oh, you mean, like obliterating any trace of monsters such as IE6 from the planet? I'd love to hear your proposals.


    I say we take off and nuke it from orbit. It's the only way to be sure.
  • gallier2 2011-09-26 14:41
    the beholder:
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
    Whoa there. You may feel entitled to post your code correction here and there's nothing wrong with it per se, but there's a side effect you should consider whenever you do that.

    I've seen a few TDWTF articles over the years where someone posts new code to do whatever the article's code was supposed to. Unfortunately the code posted was broken too and in a too obvious way; and then people started posting their (for the most part completely wrong) solutions to a problem they didn't even understand. I think this last one regarded memory management in C, AFAICR.

    There were obvious syntactic and logical errors all around but above all their code didn't even touch the requirements. I stopped reading after I saw that it was the freaking third page and people were still posting flawed code even after someone got it right on the end of first page. It was impossible to find smart comments in the middle of it all.

    I believe frits is trying to discourage this sort of behavior here. It's sort of an unwritten rule, and I support it fully.



    I don't, and now?
  • gallier2 2011-09-26 14:41
    gallier2:
    trtrwtf:
    gallier2:
    Bye, bye


    Quickest meltdown in tdwtf history?
    Guy went to pieces so fast he took out Nagesh with the shrapnel!

    (stolen, yes, but stolen with love)


    That's what you think.


    Hey, there's only room for one fake gallier2 around here, and I'm him.
  • Matt Westwood 2011-09-26 14:42
    me:
    Produce is chicken wing. With wing bark. No Qautk.

    +1 FTW
  • gallier2 2011-09-26 14:44
    gallier2:
    the beholder:
    gallier2:
    frits:
    This isn't Stack Overflow. Nobody is actually trying to correct or improve the code. Except you.


    Eat shit.
    You're not in charge of defining what is appropriate or not to post on this blog.
    Whoa there. You may feel entitled to post your code correction here and there's nothing wrong with it per se, but there's a side effect you should consider whenever you do that.

    I've seen a few TDWTF articles over the years where someone posts new code to do whatever the article's code was supposed to. Unfortunately the code posted was broken too and in a too obvious way; and then people started posting their (for the most part completely wrong) solutions to a problem they didn't even understand. I think this last one regarded memory management in C, AFAICR.

    There were obvious syntactic and logical errors all around but above all their code didn't even touch the requirements. I stopped reading after I saw that it was the freaking third page and people were still posting flawed code even after someone got it right on the end of first page. It was impossible to find smart comments in the middle of it all.

    I believe frits is trying to discourage this sort of behavior here. It's sort of an unwritten rule, and I support it fully.


    Yeah, well you're a big poopyhead too.


    Thank you to stand in for me, but I woudn't have come up with 'poopyhead'. I have to admit though, that I like it.
  • gallier2 2011-09-26 14:47
    gallier2:
    gallier2:
    trtrwtf:
    gallier2:
    Bye, bye


    Quickest meltdown in tdwtf history?
    Guy went to pieces so fast he took out Nagesh with the shrapnel!

    (stolen, yes, but stolen with love)


    That's what you think.


    Hey, there's only room for one fake gallier2 around here, and I'm him.


    This one isn't fake (can be noticed in my approximative english and my overly pedantic rants).
  • Matt Westwood 2011-09-26 14:50
    hoodaticus:
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".


    yeah, you could - you could even do it in one hit - but that could cause there to be a simultaneous change to a score of deployed production databases, a whole host of configuration files etc yada yaya. Far better solution to put something like the above in, then once the code is there to allow both spellings (correct and incorrect), you can go through the various production systems and raise a change-ticket on each one in turn, do one a weekend till they're all done.

    BTDTBTFTS on a system that had a similar problem with spelloes. I still contend that if computer programmers know they're dyslexic, they pass their work over to a literate colleague whose job it is to correct their fucking stupid mistakes. Not to do *that* is the real WTF.
  • Matt Westwood 2011-09-26 14:51
    gallier2:
    gallier2:
    gallier2:
    trtrwtf:
    gallier2:
    Bye, bye


    Quickest meltdown in tdwtf history?
    Guy went to pieces so fast he took out Nagesh with the shrapnel!

    (stolen, yes, but stolen with love)


    That's what you think.


    Hey, there's only room for one fake gallier2 around here, and I'm him.


    This one isn't fake (can be noticed in my approximative english and my overly pedantic rants).


    If they're unregistered they're fake, so fuck off both of you shitheads.
  • Matt Westwood 2011-09-26 14:53
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.
  • gallier2 2011-09-26 15:15
    Matt Westwood:
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.


    Yeah, well that's probably because you're a stinky-foot duck-plucker.
  • Danimal 2011-09-26 15:26
    D-Coder:
    Danimal:
    "A lot of students only go to school three quarters a year," Bob writes, "so maybe the author thought a business might take a summer off. Or try to squeeze another one in."

    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }


    The REAL WTF is that there are always 4 quarters in a year. There could be 3 trimesters, though.
    I'm voting this one the least WTF-y of the bunch. QUARTERS_IN_A_YEAR explains exactly why this number is here. Words are more explanatory than numbers in almost all cases.

    A word is worth 1,000 numbers.


    Man, we should all be writing GUIs.
  • SimonT 2011-09-26 15:58
    86400 seconds? I'm guilty of that!!!!!
  • DWalker59 2011-09-26 16:06
    Helena Handcart:

    It looks like gallier2 wrote the original code, and feels guilty for it. To make amends he's posted a super-efficient rewrite in the hope of saving his soul. He's bound to get shirty if you go and pooh-pooh his considerable efforts. I for one will be implementing his visionary rewrite just as soon as I can.

    Now, where's the upvote button?


    He's bound to get shirty? What's that, and how do I get that way?
  • Chris 2011-09-26 17:25
    I came here to say the same thing.
  • Tau 2011-09-26 17:34
    Matt Westwood:
    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.

    If you're working out the value of pi by measuring a real circle, then he's right - though most of the time you don't actually need that kind of precision. It's not going to change the first ten or twenty decimal places.

    If you calculate it from first principles, then he's wrong.

    Where did you get your pi?
  • Matt Westwood 2011-09-26 17:35
    gallier2:
    Matt Westwood:
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.


    Yeah, well that's probably because you're a stinky-foot duck-plucker.


    Good grief, that's a bit personal. Let me put it on record that I do *not* pluck ducks. Chickens, maybe, but never ducks. No quack.
  • Max 2011-09-26 18:06
    'Is a single-qauted string' is a single-qauted string.
  • Matt Westwood 2011-09-26 18:25
    Tau:
    Matt Westwood:
    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.

    If you're working out the value of pi by measuring a real circle, then he's right - though most of the time you don't actually need that kind of precision. It's not going to change the first ten or twenty decimal places.

    If you calculate it from first principles, then he's wrong.

    Where did you get your pi?


    The only time you "work out pi by measuring a real circle" is when you're in grade school with a dippy old bat handing out yarn and cocoa tins.

    In contemporary mathematics, Pi is not defined as the ratio of a circumference to a diameter. One of its properties is that in the Euclidean plane, circles satisfy that famous relationship. In the non-Euclidean plane, circles fail to have that property - but you don't go redefining pi according to the particular curvature of the frame of reference you happen to be using at the time. That's even more fucking stupid than confusing "its" and "it's".

    A simple way to define pi is pi/4 = 1 - 1/3 + 1/5 - 1/7 ... but it's impractical (and I may even have got it wrong - hey it's late here and I can' be bothered to look it up).
  • Matt Westwood 2011-09-26 18:26
    Max:
    'Is a single-qauted string' is a single-qauted string.


    +1 for the quine.
  • Phew 2011-09-26 18:35
    WC:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Thanks. I was starting to doubt my sanity on that one because I could not imagine the ugly if statement required to validate that in the same way.

    Not just me then....

    I'm trying to picture the single 'if' myself....
  • Jimmy 2011-09-26 18:45
    eVil:
    Plus its fine to break out of a for loop, so long as its obvious why you're breaking, and the loop isn't horrendously complicated.

    People just *think* that its bad practice, because it similar to using 'goto's in a way... however it is a very specific form of goto.... eg one that doesn't cause a spaghetti-code problem.

    This x 100.

    Too foten we see people saying "That's bad because my lecturer (or some guru I used to work for) says so.
    Misusing anything (as we have seen in the past) is probably bad practice, but that's not to say that all usage is bad practice.
  • Mick 2011-09-26 18:56
    PleegWat:
    I've got one colleague who tends to write things like #define N_HR 24. I've got another who tends to sprinkle magic numbers like 86400 (seconds per day) all over the place. Guess what I prefer maintaining...

    There is a difference (that people seem to miss) between "Magic Numbers should be avoided" and "Magic numbers should never be used".

    7 days in a week, 24hour in a day, 60 minutes in an hour, 60 seconds in a minute etc. Not really expecting any of these to change, and I have little issue (provided they use comments) with these being magic numbers (especially when people get to 86400). Maybe something like:

    /* Convert from days into seconds */
    whatever_in_seconds = whatever_in_days * 24 * 60 * 60;

    I would hope programmer's can work out what 24, 60, 60 mean
    here, even if I have worked with some who might struggle with 86400
    Of course, I could also handle it as

    whatever_in_seconds = whatever_in_days * HRS_IN_DAY * MIN_IN_HR * SEC_IN_MIN;

    but this feels a little cumbersome for a fairly straightforward calculation
  • Sh!tSt!rrer 2011-09-26 19:04
    gallier2:
    WC:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    Thanks. I was starting to doubt my sanity on that one because I could not imagine the ugly if statement required to validate that in the same way.


    As always the RWTF are the comments.

    integer ival = cint(val)
    bolMatch = (ival >= 3000 and ival <= 3299) or
    (ival >= 3351 and ival <= 3441) or
    (ival >= 5964 and ival <= 5969)

    In the worst case the original does:
    394 loop (compare+increment) + 394 comparisons + 2*394 int conversions.
    In the best case it does:
    96 loop (compare+increment) + 96 comparisons + 2*96 int conversions. (if it finds the value in the first loop, the other loops are executed).

    My implementation has in the best case 2 comparisons + 1 conversion in the best case (if that unrecognized language has short cut evaluation) and at most 6 comparisons and 1 conversion.


    Uhm....In the best case, the loop does a single comparison (what does "exit for" do?

    Either way, 1576, 384, 3,7. THey're all constant....O(1).








    <disclaimer> I AM BEING SILLY, BUT FEEL FREE TO ADD YOUR OWN LECTURES ON BIG-O NOTATION ANYWAYS....
  • Mwah 2011-09-26 19:16
    Jay:
    I don't think the QUARTERS_IN_YEAR is all that dumb.

    Sure,


    String[] quarters=new String[QUARTERS_IN_YEAR]


    probably adds nothing to the comprehensibility of the code over


    String[] quarters=new String[4]


    I'm sure anyone smart enough to understand the code can figure out that 4 is the logical number of quarters and requires no further explanation.

    But what happens when we get a little farther in the code and we come across a statement that reads:


    for (int n=0;n<4;++n)


    Now a reader might well ask, Why 4? What is this counting over? What's magic about 4? But:


    for (int n=0;n<QUARTERS_IN_YEAR;++n)


    makes the intent clear.

    And once we create such a symbolic constant, we ought to use it everywhere. Do we really want to go through the code and say, "Oh, here it's obvious why we're using 4 so I'll hard-code the number, but over here it's ambiguous, so I'll use the symbolic constant. And this one, hmm, that's debateable, I'd better take a survey of all the programmers in the department and see how many understand the intent if I hard-code the constant." That would be a massive waste of thinking time. Once you've created the constant, just use it.

    The above is doubly true for constants that might change. In the case of quarters, okay, it's not likely that we'll have a calendar reform and start having 5 quarters in a year. (Though another poster did bring up a case where he in fact had to deal with 3 quarters in a year.) But if it's something like, say, number of regions, if some places that's hard-coded and some place we use a symbol, and then we change the number of regions, someone could easily be fooled into thinking that changing the constant solves the problem.
    Constants to replace numbers for clarity mean the code is poorly commented.
    Constants should instead be used for values that are constant at execution time, but may one day need changing for a future build, or to define a default, eg:

    #define DEFAULT_TIMEOUT 100

    We can change this value for a future build if we find 100 is insufficient. While the actual setting might be read from a config file, we set up this value in case there is nothing present in the config:

    int _timeout = getTimeout(configFile);
    /* We have a range of errors that are returned as negative numbers, but we don't care here about them much, to be honest */
    if(_timeout < 0) _timeout = DEAFULT_TIMEOUT;

    Things that are constant in the world (number of quarters in a whole, for example) are usually expressed more efficiently as numbers, with a clarifying comment as necessary....
  • Mwah 2011-09-26 19:17
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.

    And how does using a constant fix that problem?
  • sdfhtsr 2011-09-26 19:19
    trtrwtf:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.



    365%52 != 0
    Years aren't composed of weeks - a given date is within week N of a given year, determined by Julian date and your conception of where the week is bounded. If your calendar of the year has a set number of weeks you're doing something wrong.

    Maybe we could try:
    #define DAYS_IN_MOTH = (approx 30)
  • Mwah 2011-09-26 19:20
    Jerry:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    Weeks don't fit into months or years, months aren't all the same size, even years have a variable number of days... and don't get me started with hours minutes and seconds that don't multiply by something reasonable but instead by 24 or 60... human time reckoning is a mess!

    What is needed is to replace all time measurements and expressions by a simple integer counter of http://en.wikipedia.org/wiki/Planck_time since the Big Bang.

    OK we might have to show it in hex instead of decimal, so it doesn't take up quite so much room.

    Whoa....I was with you until you started picking on hours and minutes.
    24 and 60 are awesome numbers, because they are evenly divisible by a lot more than 10 or 100....
  • Korn 2011-09-26 19:26
    Matt Westwood:
    hoodaticus:
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".


    yeah, you could - you could even do it in one hit - but that could cause there to be a simultaneous change to a score of deployed production databases, a whole host of configuration files etc yada yaya. Far better solution to put something like the above in, then once the code is there to allow both spellings (correct and incorrect), you can go through the various production systems and raise a change-ticket on each one in turn, do one a weekend till they're all done.

    BTDTBTFTS on a system that had a similar problem with spelloes. I still contend that if computer programmers know they're dyslexic, they pass their work over to a literate colleague whose job it is to correct their fucking stupid mistakes. Not to do *that* is the real WTF.
    It was while mocking dyslexic programmers that we came up with the idea of fi and esac. I would have liked to use pool for loops, but people feared it might confuse the users....
  • Kristie 2011-09-26 19:27
    Matt Westwood:
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.
    I think he's right - but I don't think the universe is flat.
  • Maurits 2011-09-26 20:48
    An excellent chance to show off VB's "Select Case" awesomeness:


    Select Case CInt(Val)
    Case 3000 To 3299: bolMatch = True
    Case 3351 To 3441: bolMatch = True
    Case 5964 To 5969: bolMatch = True
    End Select

  • Coyne 2011-09-27 00:25
    So, would getQuarters() work for the Maya calendar? I'm just not sure.



    Which reminds me of my contribution to humor at work earlier this year. I created a script that converts mm/dd/ccyy dates to the Mayan calendar (long and calendar round); and also converts long-count dates (lc.lc.lc.lc.lc) back to mm/dd/ccyy.

    Then I wrote this deadpan tip on how to use the command to prepare for our upcoming conversion to the Maya calendar (because of the end of the world in 2012, of course) and sent it to everyone...

    ...on April Fools of course.

    Some people thought I was serious, even though I mentioned at the end of the article that, if they questioned my sanity, they should take a closer look at the date at the top of the article.
  • D-Coder 2011-09-27 00:36
    Matt Westwood:
    gallier2:
    Matt Westwood:
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.


    Yeah, well that's probably because you're a stinky-foot duck-plucker.


    Good grief, that's a bit personal. Let me put it on record that I do *not* pluck ducks. Chickens, maybe, but never ducks. No quack.
    You should consider it. "Once you try quack, you'll never go back."
  • trtrwtf 2011-09-27 00:46
    D-Coder:
    Matt Westwood:
    gallier2:
    Matt Westwood:
    hoodaticus:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    I like how c is slowing down as magnetic force increases. That's what I think of as a non-obvious non-constant.

    52 weeks in a year not being a constant is about as obvious as it gets.


    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.


    Yeah, well that's probably because you're a stinky-foot duck-plucker.


    Good grief, that's a bit personal. Let me put it on record that I do *not* pluck ducks. Chickens, maybe, but never ducks. No quack.
    You should consider it. "Once you try quack, you'll never go back."


    I'm not the pheasant plucker, I'm the pheasant plucker's mate
    And I'm only plucking pheasants 'cause the pheasant plucker's late.

    I'm not the pheasant plucker, I'm the pheasant plucker's wife
    We're all day plucking pheasants, it's a pheasant plucking life.
  • The Outsorcerer 2011-09-27 02:11
    SCSimmons:
    "A lot of students only go to school three quarters a year," Bob writes, "so maybe the author thought a business might take a summer off. Or try to squeeze another one in."

    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }

    Am I missing something? This seems to me to return a four-element array of strings, getQuarters(0) is "1", (1) is "2", (2) is "3", and (3) is "4"; it may be confusing and ugly, but still should work & not leave out any quarters ... Mostly just an illustration of why not to be rigid about your indexing standards.

    I'd compile it and verify, but I have a long-standing policy of not copying any code from this site for any purpose.


    I use code from this site all the time. It's always way better than my own.
  • frink 2011-09-27 03:08
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.

    As opposed to just sending everyone home for that week and pretending it never happened?
  • frink 2011-09-27 03:11
    trtrwtf:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.



    365%52 != 0
    Years aren't composed of weeks - a given date is within week N of a given year, determined by Julian date and your conception of where the week is bounded. If your calendar of the year has a set number of weeks you're doing something wrong.


    isn't that exactly what he just said?!
  • Watson 2011-09-27 03:26
    trtrwtf:
    I'm not the pheasant plucker, I'm the pheasant plucker's mate
    And I'm only plucking pheasants 'cause the pheasant plucker's late.

    I'm not the pheasant plucker, I'm the pheasant plucker's wife
    We're all day plucking pheasants, it's a pheasant plucking life.


    I'm not the pheasant plucker, I'm the pheasant plucker's son,
    And I will not pluck the pheasants 'til the pheasant plucker comes.
  • Aufgehaben 2011-09-27 03:55
    I usually just write: // Here be dragons!
    That does the trick.
  • Matt Westwood 2011-09-27 03:58
    Mick:
    PleegWat:
    I've got one colleague who tends to write things like #define N_HR 24. I've got another who tends to sprinkle magic numbers like 86400 (seconds per day) all over the place. Guess what I prefer maintaining...

    There is a difference (that people seem to miss) between "Magic Numbers should be avoided" and "Magic numbers should never be used".

    7 days in a week, 24hour in a day, 60 minutes in an hour, 60 seconds in a minute etc. Not really expecting any of these to change, and I have little issue (provided they use comments) with these being magic numbers (especially when people get to 86400). Maybe something like:

    /* Convert from days into seconds */
    whatever_in_seconds = whatever_in_days * 24 * 60 * 60;

    I would hope programmer's can work out what 24, 60, 60 mean
    here, even if I have worked with some who might struggle with 86400
    Of course, I could also handle it as

    whatever_in_seconds = whatever_in_days * HRS_IN_DAY * MIN_IN_HR * SEC_IN_MIN;

    but this feels a little cumbersome for a fairly straightforward calculation


    Yes but there's more to it than that. If you need to use 24 or 60 in another context, it's important to understand which 24 and which 60 are used in each particular context. If you needed at one point to investigate the 60 used in the other context, you don't want to have to get it mixed up (especially with a "search" tool) for the places where you might have hard-wired the number of seconds in a day ("because that's never going to change"). So if I saw code where 60 was used as a magic number for number of seconds in a day, I'd change it to use a parameter. No quack.
  • Matt Westwood 2011-09-27 04:01
    Korn:
    Matt Westwood:
    hoodaticus:
    Iceman:

    if (GlobalConfig["UseSpellingError"])
    {
    pKey = pKey.replace("gb_custom", "gb_costum");
    }


    This not a WTF. This is normally used when a old version of some config file used a config option with a spelling error. In a new version you fix the spelling error, but have a compatible option for the old spelling. This way you don't need to update all config files everywhere, but new files will be correct. This is called backward compatibility.
    Or you could make it work properly. This is called "fixing the problem".


    yeah, you could - you could even do it in one hit - but that could cause there to be a simultaneous change to a score of deployed production databases, a whole host of configuration files etc yada yaya. Far better solution to put something like the above in, then once the code is there to allow both spellings (correct and incorrect), you can go through the various production systems and raise a change-ticket on each one in turn, do one a weekend till they're all done.

    BTDTBTFTS on a system that had a similar problem with spelloes. I still contend that if computer programmers know they're dyslexic, they pass their work over to a literate colleague whose job it is to correct their fucking stupid mistakes. Not to do *that* is the real WTF.
    It was while mocking dyslexic programmers that we came up with the idea of fi and esac. I would have liked to use pool for loops, but people feared it might confuse the users....


    Unfortunately in some more-or-less important application languages, "fi" is a reserved word for what in sane languages is indicated by "end if" or the closing of a curly.
  • Idu Knowski 2011-09-27 04:34
    This needs to be optimized:

    for j=0 to 4294967295
    for i=3000 to 3299
    if cint(j)=cint(i) then
    bolMaybeMatch=true
    exit for
    end if
    next

    for i=3351 to 3441
    if cint(val)=cint(i) then
    bolMaybeMatch=true
    exit for
    end if
    next

    for i=5964 to 5969
    if cint(val)=cint(i) then
    bolMaybeMatch=true
    exit for
    end if
    next

    if bolMaybeMatch and cint(val)=cint(j)
    bolMatch=true
    exit for
    end if
    next
  • Jesper 2011-09-27 05:08
    I always signle quat my strings. I like nicely qauted strings. What's wrong with that?
  • iMalc 2011-09-27 05:13
    "while reconfiguring Sybase stored procedures for a custom version of an HL7 interface application, I stumbled upon this useless-yet-used everywhere procedure."

    That's clearly the result of something that got refactored and probably previously did something else. You think management wants the programmer to rip it out everywhere, taking extra time and potentially introducing a bug, when it could just be left as-is after it got refactored into nothingness? Heaven forbid it ever became needed to do something more complex again.
  • Neil 2011-09-27 06:14
    Max:
    'Is a single-qauted string' is a single-qauted string.
    No.

    "Is a sentence fragment" is a sentence fragment.

    ''Is a single-qauted string'' is a single-qauted string. Of course I single-qauted the string, so there are no escape characters.

    CAPTCHA: bene there, done that.
  • Steve The Cynic 2011-09-27 07:30
    Mick:
    Maybe something like:

    /* Convert from days into seconds */
    whatever_in_seconds = whatever_in_days * 24 * 60 * 60;

    I would hope programmer's can work out what 24, 60, 60 mean
    here, even if I have worked with some who might struggle with 86400
    Of course, I could also handle it as

    whatever_in_seconds = whatever_in_days * HRS_IN_DAY * MIN_IN_HR * SEC_IN_MIN;

    but this feels a little cumbersome for a fairly straightforward calculation

    But the advantage of the symbolic names is that they help you escape from the trap of writing non-portable code.

    In C, 24*60*60 == what?

    If you answer 86400, take a portability penalty.

    If you answer "It depends on the size of int", congratulations. On 16-bit systems (not so may of those around now, I know, but bear with me), 24*60*60 is 20864, even in "long seconds = 24*60*60;". (Listen to the voice of experience, and bear in mind that I haven't had any reason to deal with C99, so I don't know if it is different there.)

    If you use the symbolic constants, you can stick an L in one of them (probably HRS_IN_DAY), and then the result of the multiply will be a long everywhere you use it, and consequently it will be 86400. You will never have to track down the one place where the multiplication got 16-bitted because you left off the L.

    Further note: #define SECS_IN_DAY 86400 will work correctly, as the compiler will expand the constant to be a long.
  • PedanticCurmudgeon 2011-09-27 08:45
    Steve The Cynic:
    But the advantage of the symbolic names is that they help you escape from the trap of writing non-portable code.

    In C, 24*60*60 == what?

    If you answer 86400, take a portability penalty.

    If you answer "It depends on the size of int", congratulations. On 16-bit systems (not so may of those around now, I know, but bear with me), 24*60*60 is 20864, even in "long seconds = 24*60*60;". (Listen to the voice of experience, and bear in mind that I haven't had any reason to deal with C99, so I don't know if it is different there.)

    If you use the symbolic constants, you can stick an L in one of them (probably HRS_IN_DAY), and then the result of the multiply will be a long everywhere you use it, and consequently it will be 86400. You will never have to track down the one place where the multiplication got 16-bitted because you left off the L.

    Further note: #define SECS_IN_DAY 86400 will work correctly, as the compiler will expand the constant to be a long.
    This brings back horrific memories of VB6 applications suddenly breaking shortly after a primary key column gets past 32000.
  • Anon 2011-09-27 09:26
    Sh!tSt!rrer:
    gallier2:

    integer ival = cint(val)
    bolMatch = (ival >= 3000 and ival <= 3299) or
    (ival >= 3351 and ival <= 3441) or
    (ival >= 5964 and ival <= 5969)

    In the worst case the original does:
    394 loop (compare+increment) + 394 comparisons + 2*394 int conversions.
    In the best case it does:
    96 loop (compare+increment) + 96 comparisons + 2*96 int conversions. (if it finds the value in the first loop, the other loops are executed).

    My implementation has in the best case 2 comparisons + 1 conversion in the best case (if that unrecognized language has short cut evaluation) and at most 6 comparisons and 1 conversion.


    Uhm....In the best case, the loop does a single comparison (what does "exit for" do?


    "exit for" exits the current for loop. However, the original code has 3 "for" loops, and the second and third loops will run even if we exited the first "for" loop. In fact, if we exited the first "for" loop, then we are guaranteed to go through the second and third loops completely - we can't possibly match the tests in those loops, so we cannot possibly end them early.
  • NotLeo 2011-09-27 09:27
    Abso:
    Leo:

    #define THREE_THOUSAND 3000
    #define THREE_THOUSAND_ONE 3001
    #define THREE_THOUSAND_TWO 3002
    ...
    #define THREE_THOUSAND_THREE_HUNDRED_FIFTY_ONE 3351

    if cint(val)=cint(THREE_THOUSAND) then
    bolMatch=true
    end if
    if cint(val)=cint(THREE_THOUSAND_ONE) then
    bolMatch=true
    end if
    ...

    FTFY.

    This post has been sponsored by your grade three teacher.


    I guess it depends what language you're using for identifiers. If you use English, then THREE_THOUSAND_AND_ONE is correct. If you use American, then you might prefer THREE_THOUSAND_ONE.
  • forgottenlord 2011-09-27 09:41
    Being in the education software industry, I can say with certainty that there are definitely cases where you'll need all 4 quarters. Why you've hard coded the number of terms, however, doesn't make sense to me. Why you've called it quarters makes even less sense.
  • eVil 2011-09-27 09:54
    NotLeo:
    Abso:
    FTFY.

    This post has been sponsored by your grade three teacher.


    I guess it depends what language you're using for identifiers. If you use English, then THREE_THOUSAND_AND_ONE is correct. If you use American, then you might prefer THREE_THOUSAND_ONE.


    Its pretty amusing when Americans choose to correct something when they're just wrong.

    We know they're wrong because they claim their speaking English, but getting all the rules mixed up.

    If you want to correct us on our own language, please remember that you are simply wrong, and your "4th Year" teacher probably ought to have explained that cultural truism to you. Although, had you started Kindergarten a year earlier, maybe you wouldn't have been a year behind your entire life, and might have worked this out for yourself.

    *Bows* I thank you! *Bows*
  • eVil 2011-09-27 09:55
    Also - I know I made some terrible spelling mistakes in the pos above, but frankly, since its my language, I have carte blanche to abuse it how I like... including via the inclusion of french (lower case F intentional).
  • GoatCheez 2011-09-27 12:57
    Alex, you're slacking.
    QUARTERS_IN_A_YEAR isn't really a wtf, and certainly doesn't fail as has been pointed out. I can see very valid reasons for wanting strings representing the index of a quarter starting from one, when still referencing them in code by 0. If, for example, you were to display to a user "Quarter #X", you wouldn't want to display 0-3, but 1-4. This function retrieves an array for such a use.

    Also,

    "// Get today's date, and also format it in a more human-friendly way"

    was posted twice.

  • the beholder 2011-09-27 13:36
    gallier2:
    the beholder:
    <snip>


    Yeah, well you're a big poopyhead too.
    That's so childish! Besides, I am rubber, you are glue... ;)
  • Jay 2011-09-27 14:38
    trtrwtf:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.



    365%52 != 0
    Years aren't composed of weeks - a given date is within week N of a given year, determined by Julian date and your conception of where the week is bounded. If your calendar of the year has a set number of weeks you're doing something wrong.


    Ummm ... I think that was my point.
  • Jay 2011-09-27 15:02
    Jerry:
    Jay:
    BTW, even seemingly obvious constants are not always so obvious. Like, how many weeks are in a year? Obviously 52, right? Well, not really, there are 52 weeks plus an extra day, 2 in leap years. My previous employer dealt with that by every 4 or 5 years having 53 weeks in the calendar.
    Weeks don't fit into months or years, months aren't all the same size, even years have a variable number of days... and don't get me started with hours minutes and seconds that don't multiply by something reasonable but instead by 24 or 60... human time reckoning is a mess!

    What is needed is to replace all time measurements and expressions by a simple integer counter of ttp://en.wikipedia.org/wiki/Planck_time since the Big Bang.

    OK we might have to show it in hex instead of decimal, so it doesn't take up quite so much room.


    Here's my suggestion: http://johansens.us/sane/offthewall/cal.htm

    Shut up, Akismet!
  • qbolec 2011-09-27 18:42
    As to:

    String[] quarters = new String[QUARTERS_IN_A_YEAR];

    I think I know languages in which this creates :
    a) a 3 character long string with trailing \0 character, making the length equal to 3
    b) a 4 pseudo random characters which happen to lay in the uninitialized memory, making the length anyhting between 0 and .. Segfault
    c) a 4 bytes array initialized with all zeros, making the length equal to 0

    but what I am really interested in is your debate about magic constants!

    P.S. in what language does it define a string of length 4?
  • Cpt. Repeatable 2011-09-27 19:43
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);

  • I. G. E. 2011-09-27 21:01
    qbolec:
    As to:

    String[] quarters = new String[QUARTERS_IN_A_YEAR];

    I think I know languages in which this creates :
    a) a 3 character long string with trailing \0 character, making the length equal to 3
    b) a 4 pseudo random characters which happen to lay in the uninitialized memory, making the length anyhting between 0 and .. Segfault
    c) a 4 bytes array initialized with all zeros, making the length equal to 0


    I wonder what those might be. Doesn't compile in C or C++ (unless there's obscene preprocessor abuse going on, in which case it could do anything), in C# and Java it creates a string array of length four. It needs C-ish syntax, so we can exclude Python, Haskell, O'Caml, Lisp, VB, Brainfuck, Malbolge, Befunge, ...
    I'm not sure whether Perl or PHP would accept it, I think they wouldn't. Javascript perhaps, but if it does, it would behave more like C# and Java.

    P.S. in what language does it define a string of length 4?

    Not in any commonly used. The language in the article seems to be Java, so it creates a String array of length four, as one would expect.
  • JustSomeGuy 2011-09-27 22:29
    Actually, something like:
    if (GlobalConfig["UseSpellingError"])
    
    pKey = pKey.replace("gb_custom", "gb_costum");
    has a valid use case. Specifically, when fixing problems in the field that are causing problems for one customer, the *worst* thing you can do is to introduce problems for all your other customers.

    So what you do is to add a configuration option to use the new behaviour. Anyone who doesn't care or who, for some reason, has come to rely on the "errant" behaviour, remains untouched. All those who complain (including the customer you're fixing the problem for) are told to add that particular configuration option.

    Ideally, it's cleaned up in the next major release, but this almost never happens :-)
  • Eternal Density 2011-09-28 02:35
    silent d:
    dgvid:
    D-Coder:
    ... Words are more explanatory than numbers in almost all cases.

    A word is worth one-thousand numbers.


    FTFY


    #define NUMBER_OF_NUMBERS_THAT_A_WORD_IS_WORTH 1000
    So the picture that's worth a thousand words must be a megapixel since each word is worth a thousand numbers.
  • Kef Schecter 2011-09-28 04:45
    Funny... NoScript didn't like the URL of this article. Thought it was some kind of XSS attack. I have verified that, yes, it really is the URL that's the problem, since I created a dummy file on my own webserver with the same filename, no JS or anything at all in it, and it reported the same thing.
  • realmerlyn 2011-09-28 05:11
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    You have a strange definition of "efficient". Remind me not to hire you.
  • eVil 2011-09-28 09:10
    realmerlyn:
    eVil:
    A sinlge if could probably do the job, but surely you'd have to write some pretty inglorious code to achieve that.

    As it stands, the code is readable and efficient, so I dont see what you'd gain by refactoring it?


    You have a strange definition of "efficient". Remind me not to hire you.


    May I also remind you to read the rest of the thread? All is explained.
  • NotJamieZawinski 2011-09-28 14:08
    "While looking through some old code, I found this snippet that creats a 'human friendly' date to display to the user," Adam Smith writes, "perhaps this is more efficient than date('d/m/Y')."

    // Get today's date, and also format it in a more human-friendly way
    $date = date("Y-m-d");
    $nicedate = preg_replace("/(....).(..).(..)/","$3/$2/$1",$date);


    “Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.” - Jamie Zawinski
  • gilgamash 2011-09-29 04:39
    I think the only problem here is, that it is not written as a recursive function...


    for i=3000 to 3299
    if cint(val)=cint(i) then
    bolMatch=true
    exit for
    end if
    next

    for i=3351 to 3441
    if cint(val)=cint(i) then
    bolMatch=true
    exit for
    end if
    next

    for i=5964 to 5969
    if cint(val)=cint(i) then
    bolMatch=true
    exit for
    end if
    next

  • Jay 2011-09-29 13:25
    Mwah:
    Constants to replace numbers for clarity mean the code is poorly commented. ... Things that are constant in the world (number of quarters in a whole, for example) are usually expressed more efficiently as numbers, with a clarifying comment as necessary....


    I humbly beg to disagree.

    Sure, instead of writing:


    final static float PI=3.1415926;
    ...
    if (angle>PI/4) ...


    We could write


    if (angle>0.78539815) // value is pi/4


    But why is (b) better than (a)?

    In simple human psychology, once you define a constant, it's a lot easier to get programmers to use it, then to get them to add a comment. They have to write SOME value to get the code to work, and it's no more effort to type in the name of the constant than to type in the value. But writing a comment is always extra effort.

    Also, using named constants enforces consistency. Suppose we find one comment that refers to "top speed" and another that refers to "maximum velocity". Are these the same thing or two different things? With a named constant, the programmer would have to use the exact same name. (I suppose he could create two named constants with the same value, but that would require extra effort and thus be less likely.)

    I'm all for writing good documentation, and I don't buy the argument that "good code is self-documenting". But I don't see any reason to go out of our way to make the code LESS self-documenting and then make up for it with more comments or external documentation.
  • Jay 2011-09-29 13:30
    Matt Westwood:

    I shared an office with someone who suggested that the value of pi will change if they discover the universe isn't flat. I never was able to persuade him he was talking bollocks.


    Hmm, considering that the value of pi was discovered in this universe, it's hard to see how any new knowledge about the nature of the universe could change the value of pi. Perhaps we could learn that there are other possible universes with a different value for pi, but that's not what your friend is saying at all.
  • Randy Snicker 2011-10-01 19:36
    the beholder:
    gallier2:
    the beholder:
    <snip>


    Yeah, well you're a big poopyhead too.
    That's so childish! Besides, I am rubber, you are glue... ;)

    Oh, it's all right. I'm sure that we can handle this situation maturely, just like the responsible adults that we are. Isn't that right, Mr... Poopy Pants?
  • Paul 2011-10-02 18:01
    Efficient!?!?? One If statement would use 3 comparisons, whereas this uses 394 comparisons....
  • ObiWayneKenobi 2011-10-04 16:52
    Amazes me how downright stupid people are with renaming things. Unless you are coding in Notepad, modern IDEs have a "Refactor" feature that will rename all references to a particular variable/method/file/class. There should NEVER be a reason to keep a misspelled or incorrectly-named piece of code around other than developer ignorance.
  • photo shopper 2012-03-02 06:09
    Eternal Density:
    silent d:
    dgvid:
    D-Coder:
    ... Words are more explanatory than numbers in almost all cases.

    A word is worth one-thousand numbers.


    FTFY


    #define NUMBER_OF_NUMBERS_THAT_A_WORD_IS_WORTH 1000
    So the picture that's worth a thousand words must be a megapixel since each word is worth a thousand numbers.


    Well, considering todays smartphones and stuff, you might rewrite that bit to something like this (warning: assuming stuff about preprocessors, don't know exactly what they do):

    #ifdef IPHONE_3
    #define NUMBER_OF_NUMBERS_THAT_A_WORD_IS_WORTH 3000
    #elseif IPHONE_4
    #define NUMBER_OF_NUMBERS_THAT_A_WORD_IS_WORTH 8000
    ...
    #endif

    .. or something similar (numbers are aproximate too, I'm to lazy to google the exact numbers of megapixels in the cameras).
  • Rasmus 2012-04-18 10:24
    Perhaps it's just me, but I cannot see the "real error" quarter code above.


    const QUARTERS_IN_A_YEAR = 4;

    ... several codefiles later...

    private String[] getQuarters()
    {
    String[] quarters = new String[QUARTERS_IN_A_YEAR];
    for (int k = 0; k < quarters.length; k++) {
    quarters[k] = new Integer(k+1).toString();
    }
    return quarters;
    }

    To the best of my understanding, that would actually generate the following array:

    quarters[0] = "1"
    quarters[1] = "2"
    quarters[2] = "3"
    quarters[3] = "4"

    Ofc. it depends on the language used
  • Axel 2014-01-29 09:45
    Mwah:


    int _timeout = getTimeout(configFile);
    /* We have a range of errors that are returned as negative numbers, but we don't care here about them much, to be honest */
    if(_timeout < 0) _timeout = DEAFULT_TIMEOUT;

    This reminds me of http://www.ibiblio.org/harris/500milemail.html