• nameless bstrd (unregistered) in reply to tracker1

    public static List<string> GetMonths(int month) { List<string> monthList = new List<string>(); DateTime tempDate = new DateTime(2010, month, 1); DateTime endDate = tempDate.AddMonths(12); while (tempDate < endDate) { monthList.Add(tempDate.ToString("MMMM")); tempDate = tempDate.AddMonths(1); } return monthList; }

  • Anon (unregistered) in reply to Jesse Houwing
    Jesse Houwing:
    There isn't even a need to create an array with the source names of the months.

    CultureInfo already contains this. int startMonth = 6

    List<string> months = new List<string>(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.Take(12)); months = months.Skip(startMonth ).Concat(months.Take(startMonth )).ToList();

    What I do not (yet) understand is why MonthNames is 13 long to begin with...

    One month later, your boss stops by: Boss:Did you change the GetMonths code? You:Yeah, got it I18N ready and got rid of a dozen lines of offshore crap code. Is this a good time for my performance review? Boss:Performance review? Sure, you want a performance review, here's your fing performance review: a) Our biggest customer just called to complain that the months in the drop down lists are a month off. They're annoyed. Did you test your fing code? You know we use .NET here, right? You do know that DateTime uses 1 based numbers for months, right? Why did you write a f*ing zero based solution? b) Did you ask QA to test your fing code? I asked you to fix 4 minor bugs. I asked QA to test the features effected by those bug fixes. They missed the off by one month issue because they didn't know to test it. c) Do you know your code is 5 times slower than the crap from overseas? 5 f**ing times slower! What kind of crap code are you writing it's that slow? d) We have no plans to sell this product outside the US. Why are you adding I18N support when it's not on the roadmap? You:WTF just happened???

  • (cs)

    TRWTF is the subject. What does the code have to do with SQL?

    The code itself is a rather minor WTF. The technique is clumbsy and using mod 13 instead of mod 12 and then adjusting is just plain weird.

  • Anon (unregistered) in reply to dwilliss
    dwilliss:
    TRWTF is the subject. What does the code have to do with SQL?
    Nothing to do with SQL, true. (Looking up the month name each time through the loop with a SQL query would have been a true WTF). But maybe they have a bunch of SQL queries that return month as a number, and they need a list of the last 12 months based on that number. Then it starts to fall into the SQL helper category. Or maybe the programmer was just too lazy to create a new file and class just for 1 utility function. I've done that before. Not really WTF worthy.

    No, I think Alex got us on this one. The WTF is the punchline:

    Phillip added, "clearly, worrying about whether or not a particular part of the .net framework showing a warning because it had been deprecated was more important than whether or not un-managed resources were disposed of properly."
    (I'm not the first to notice this. It just took a while for it to sink in). There is not an "un-managed" resource leak here. It's C#. It garbage collects. DUH!!! This WTF, and the c-bitmap WTF from 2 days ago...aren't.

    And I bet Alex knows that. And I bet he gets a LOT of these. So I think he wanted to share, and sit back and watch the fireworks with a crap-eatin grin...

    You got us Alex....now can we get back to TRWTF?

  • AA (unregistered)

    Like I said, Alex copy-pasted the wrong code sample.

  • (cs) in reply to Daniel Migowski
    Daniel Migowski:
    This is a completely useful function. It returns the 12 month and includes a rotation, so you get the month from June to December and Januar to May, if you pass 6 (June) as an argument.

    I agree, TRWTF is not recognizing what the function does, nor that it's probably more readable and clear than taking a precomposed array and generating a new one using some weird array wraparound checks.

    This seems like a perfectly nice and legible approach.

    Except!

    No support for localization!?? In this globalized world, WTF!!!

  • (cs) in reply to Anon
    Anon:
    Or maybe the programmer was just too lazy to create a new file and class just for 1 utility function. I've done that before. Not really WTF worthy.

    ...

    This WTF, and the c-bitmap WTF from 2 days ago...aren't.

    You got us Alex....now can we get back to TRWTF?

    Is it possible that the quality of coders is generally improving over time as code reviews and open source projects force review and rework of bad code, so that there are actually fewer instances of egregious WTF-worthy code as time goes on?

  • ohno (unregistered)

    Philip thought

    1. List<string> is un-managed resources
    2. it is not disposed

    So the WTF is that Philip doesn't realize that he does not know a bit about C#.

  • Coder (unregistered) in reply to takatori
    takatori:
    Daniel Migowski:
    This is a completely useful function. It returns the 12 month and includes a rotation, so you get the month from June to December and Januar to May, if you pass 6 (June) as an argument.

    I agree, TRWTF is not recognizing what the function does, nor that it's probably more readable and clear than taking a precomposed array and generating a new one using some weird array wraparound checks.

    This seems like a perfectly nice and legible approach.

    WTF!?! It uses a 13 month list, modulo 13, it's broken for negative numbers, and it's a nice and legible approach?

    The nice and legible approach is to use the standard algorithm: modulo 12 AT THE TOP OF THE LOOP.

    In the middle of the loop you put a case statement or an array or an object or whatever floats your boat.

    It's a passible first attempt for a beginner programmer. That doesn't make it nice or legible. It makes it a dodgy kludge to get month Zero.

  • mypalmike (unregistered)

    (In Java... Not terribly efficient due to mod. Whatever.)

    public class CircularArrayList<T> extends ArrayList<T> {
      static final long serialVersionUID = 1L;
    
      public CircularArrayList( Collection<T> src ) {
        super(src);
      }
      public T get( int index ) {
        return super.get(index % 12);
      }
    }
    
    public class MonthUtil {
      public static List<String> getMonths( int month ) {
        month-=1;  // Input is 1..12 = Jan..Dec
        List<String> result = new LinkedList<String>();
        CircularArrayList<String> months = new CircularArrayList<String>( Arrays.asList( new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } ) );
        for( int i = 0; i < 12; i++ ) {
          result.add(months.get(month++));
        }
        return result;
      }
    }
    
  • (cs)

    I don't know this "C#" you youngsters speak of, but its clear that the code returns an array of month names with the 0-th element set to the requested month. Entirely useless, and probably damaging. The same result could be achieved with the client code using

    $month_names[$_month + $i + (-12*int(($_month+$i)/12))];

    with $i as the index and $_month as the requested month.

    The second part of the story I don't understand, maybe someone can enlighten me. I've often committed changes to dozens of files, where I changed the name of a single function or class to better reflect its duty. This results in a "large commit" where the actual change is in fact very small.

  • Rohan Prabhu (unregistered)

    I cannot possibly count the number of WTFs in the above CSOD.

  • (cs) in reply to takatori
    takatori:
    taking a precomposed array and generating a new one using some weird array wraparound checks.
    "Weird array wraparound checks"? WTF? You're talking about basic addition and subtraction, it's about as simple as math gets. If you find that conceptually challenging, are you sure you're not in the wrong field?
  • (cs) in reply to MikeCD
    MikeCD:
    In this case it also sounds like the lead developer is going for a warning-free codebase which is laudable.
    Exactly. First thing I did at my first job, took some time to convince people that it was much easier to spot the difference between 0 and 1 than between 632 or 633 warnings. After the discussion was over it took only a morning to fix all of them.
  • Tim Rowe (unregistered) in reply to ShatteredArm
    ShatteredArm:
    Ernie:
    Anish:
    Terry:
    Utterly riveting! What happened next?

    Seriously, a substandard but apparently working function, and someone using the 'refactor' tool in visual studio are... just completely normal. I mean the function could be better but it's not wrong. There's no wtf here. All I can say is that they were probably developing for an embedded system where no file system was available, that's all.

    Can you develop for embedded systems in .Net?

    Have you ever heard of Windows CE or Windows Mobile? Or how about Windows XPe?

    Author already established that there is a file system. The code used app settings.

    Also, the function could have been easier using LINQ syntax: List<string> months = new List<string> { "January", "Feb... months = months.Skip(month).Concat(months.Take(month)).ToList();

    Yes, but how many C# installations "back then" (or even now) supported Linq? Saying "It would have been easier using a technology that hadn't been invented then" isn't saying much.

  • Raniz (unregistered) in reply to Jesse Houwing
    Jesse Houwing:
    [...]

    What I do not (yet) understand is why MonthNames is 13 long to begin with...

    There are calendars that use a leap-month. It's supported in Java, I don't know about C#.

    http://en.wikipedia.org/wiki/Undecember#Computing[

  • Johnson (unregistered)

    This is perfectly normal on an embedded platform that perhaps doesn't have a file system.

  • Anonymous (unregistered)

    There are no unmamaged resources in that code snippet so I don't see what the last line of the article is talking about. Also, EVE Online. No wait, embedded systems, filesystem, ah shit.

  • plasmab (unregistered)

    TRWTF is that someone thought this was a WTF!

  • ath (unregistered) in reply to mk
    mk:
    The line I am curious about is
    int _month = month;

    Congratulations! You're the first one to find the WTF!

    I was focused on the last sentence "... un-managed resources were disposed of properly ..." since I couldn't see how that related to the article. Turns out it was just a decoy to hide the real WTF which was cleverly hidden right there in the code. Congrats to finding it!

    You're the proud winner of todays "Find the WTF" contest.

  • Paul (unregistered) in reply to eclipsed4utoo
    eclipsed4utoo:
    So this would be your solution? Why not have the dropdown populated with the months in the correct order, with the item's value set to the month number. Then simply auto-selecting the current month using the month number.

    What if the user wants to be able to advance the month by a number of months, say if a customer prepays for a number of months of support, and you want to set the expiry date.

    If you want to advance 8 months, with this list, you would just press 'down' 8 times.

    If you put thie months in the correct order, and start with 'June', you either have to think, and press up 4 times, or press down 6 times, then up 12 times, then down the remaining 2 times.

    Without knowing the purpose to which the function was used, we can't say whether the use was a WTF or not. But, apart from the minor wrapping algorithm, it's not really a TDWTF-worthy WTF.

  • nah (unregistered) in reply to takatori
    takatori:
    Is it possible that the quality of coders is generally improving over time as code reviews and open source projects force review and rework of bad code, so that there are actually fewer instances of egregious WTF-worthy code as time goes on?
    No.

    New bad coders are produced faster then old bad coders get reformed or removed from the pool. It's just that there are no more interesting ways do screw up that are new to the site.

  • foo (unregistered) in reply to takatori
    Is it possible that the quality of coders is generally improving over time as code reviews and open source projects force review and rework of bad code, so that there are actually fewer instances of egregious WTF-worthy code as time goes on?
    No way, I've got a lifetime's supply here...
  • Anon (unregistered) in reply to takatori
    takatori:
    Is it possible that the quality of coders is generally improving over time as code reviews and open source projects force review and rework of bad code, so that there are actually fewer instances of egregious WTF-worthy code as time goes on?

    ROTFLMAO! Congrats! You win the thread!

  • · (unregistered) in reply to metzomagic
    metzomagic:
    it could be written a lot more concisely
    You don't say?
    months = ["January", "February", "March", "April", "May", "June", "July",
      "August", "September", "October", "November", "December"]
    

    monthsFrom x = let y=(x-1)mod12 in (drop y months) ++ take y months

    Though this version works for values outside 0..12, so it's not feature equivalent.

  • bvfdshbgmnuyhrd (unregistered) in reply to Carl

    In Irish embedded development girls are definitely not WTF.

  • Anish (unregistered) in reply to Mike

    From my understanding it is a managed object. The Garbage Collector can dispose of it (free it) when it is no longer referenced.

  • PRMan (unregistered) in reply to ShatteredArm
    ShatteredArm:
    Ernie:
    Anish:
    Terry:
    Utterly riveting! What happened next?

    Seriously, a substandard but apparently working function, and someone using the 'refactor' tool in visual studio are... just completely normal. I mean the function could be better but it's not wrong. There's no wtf here. All I can say is that they were probably developing for an embedded system where no file system was available, that's all.

    Can you develop for embedded systems in .Net?

    Have you ever heard of Windows CE or Windows Mobile? Or how about Windows XPe?

    Author already established that there is a file system. The code used app settings.

    Also, the function could have been easier using LINQ syntax: List<string> months = new List<string> { "January", "Feb... months = months.Skip(month).Concat(months.Take(month)).ToList();

    TRWTF is that somebody thinks that LINQ code is preferable. It's not. It's much more difficult to see what's happening there than even in the original.

    Code is supposed to be maintainable, not "Look at how awesome I am at LINQ! I'm so awesome that Junior programmers will NEVER be able to read my code...NEVER!" Bwah, ha, ha, ha, ha (twist mustache).

  • Foo (unregistered) in reply to frits

    This is not the same function: yours don't miss a month when you pass a number higher than 12.

  • Foo (unregistered) in reply to frits
    frits:
    Other than being ugly, it's not much of a WTF. At the risk of being abused, here's how I would do it (static tests not shown):

    static List<string> m_months = new List<string>( new string[] { "January","February","March","April", "May","June", "July","August","September","October","November","December" } ); public static List<string> GetMonths(int month) { month--; List<string> months = new List<string>(); for (int i = month; i < month + 12; i++) { months.Add(m_months[i % 12]); } return months; }

    Oops: This is not the same function: yours don't miss a month when you pass a number higher than 12.

  • TRWTF_3468 (unregistered)

    Isn't the only real problem this code has is that it can be WRONG?

    If you pass in anything outside 0-12 you lose a month due to the switch statement coming before the modulo.

    i.e. GetMonths(13) only gives you a list from January-Novemeber. Missing December.

  • (cs) in reply to DaveK
    DaveK:
    Right Wing-Nut:
    HOWEVER, there is one final wtf.

    WTF kind of program architecture actually needs this sort of array to be returned? WTF is the role that this function plays in the system?

    Exactly. What kind of poltroon goes to all that length to construct arrays full of months beginning from random points when the freakin' obvious thing to do is have one single goddamn static array full of months and apply an offset modulo 12 when you look up an entry? That, ladies and gentlemen, is TRWTF.

    EDIT: The Other RTWF, as ever, is the number of brain-dead fools who think the problem is that the routine is not efficient or well coded, rather than that it exists at all. You cannot fix this problem by rewriting the subroutine but only by deleting it. You guys are all micro-optimising when you should be algorithmically optimising.

    You still missed it.

    1. As someone else pointed out, for some things you actually do need an array.

    2. There's almost certainly a standard library for the language of your choice that already has the array you want, in the language of the user's choice. So you instead use the standard library call. If you need all twelve months, you make an array of 12 elements, and then populate the elements by looping through the months, modulo 12, and calling the standard library each time. It's not only faster than the given code sample, but it's I18N compliant.

    3. Most of the people here are not trying to fix the problem, but are reveling in it. You're spoiling their fun. That's ok, so'm I.

  • vg (unregistered)

    I'm very confused. Isn't all that's require just

    package array;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class PrintMonths {
        
        private static final String[] months = {"Jan",
                "Feb",
                "March",
                "April",
                "May",
                "June",
                "July",
                "Aug",
                "Sept",
                "Oct",
                "Nov",
                "Dec"};
        
        public static List<String> getMonths(int startFromIndex) {
            List<String> result = new ArrayList<String>();
            for (int i=startFromIndex-1; i<months.length + startFromIndex-1; i++) {
                result.add(months[i % 12]);
            }
            return result;
        }
        
    
        public static void main(String[] arg) {
           System.out.println(getMonths(4));
        }
    }
        
    
    </pre>
    

    ?

    i'm not flaming or whatever, just very curious to know what all the hoopla is for. i think i missed something obvious here.

  • (cs) in reply to vg
    vg:
    I'm very confused.
    That is perfectly normal on a small embedded platform that doesn't have a filesystem.
  • (cs)
    ...
                case 12:
                    monthList.Add("Smarch"); //"Don't touch Willy." Good advice
                    break;
            }
            _month++;
            _month = (_month % 13);
            if (_month == 0)
                _month = 1;
        }
        return monthList;
    }
    

    FTFY

  • wgc (unregistered) in reply to MikeCD
    MikeCD:
    In this case it also sounds like the lead developer is going for a warning-free codebase which is laudable.

    Here! Here! (or is it Hear! Hear!?)

    --Former build nazi in hell because I can't find the real issues among the hundreds of deprecated function warnings.

  • wgc (unregistered) in reply to takatori
    takatori:
    Daniel Migowski:
    This is a completely useful function. It returns the 12 month and includes a rotation, so you get the month from June to December and Januar to May, if you pass 6 (June) as an argument.

    I agree, TRWTF is not recognizing what the function does, nor that it's probably more readable and clear than taking a precomposed array and generating a new one using some weird array wraparound checks.

    This seems like a perfectly nice and legible approach.

    Except!

    No support for localization!?? In this globalized world, WTF!!!

    The real WTF is I don't see the words "fiscal year" anywhere in all these comments (ok, I didn't read all of them, but come on ...). Doesn't anyone work for, you know, a company?

    This looks like something that may be helpful for translating any fiscal year back to calendar year.

  • Anonymous (unregistered) in reply to gray goat
    gray goat:
    Most likely off by one, but: private static List<string> GetMonthsStartingFrom(int startingMonth) { var months = new List<string> { {"Jan"}, {"Feb"}, {"March"}, {"April"}, {"May"}, {"June"}, {"July"}, {"Aug"}, {"Sept"}, {"Oct"}, {"Nov"}, {"Dec"}, {"Jan"}, {"Feb"}, {"March"}, {"April"}, {"May"}, {"June"}, {"July"}, {"Aug"}, {"Sept"}, {"Oct"}, {"Nov"} }; startingMonth = startingMonth % 12; return months.GetRange(startingMonth, 12); }

    This made me laugh.

    mk:
    The line I am curious about is
    int _month = month;
    Is there a legitimate reason to do this in C#? In C or C++, I can't think of one. If the parameter month were a pointer and the program multithreaded, this would make sense. However, the parameter is an int, so there's no way that another thread could change. Moreover, there is nothing wrong with reassigning to your parameters, in C at least.

    Convention? To not modify parameters.

  • Toettoe (DE) (unregistered)

    nearly anybody used the chance to create a generic method, so here we go:

    var laMonthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.Take(12).ToList();

    // month are 0-index based here, so 6 means July foreach (string lsMonth in laMonthNames.EnumerateRotated(6)) { Console.WriteLine("Month: " + lsMonth); }

    // the target is to enumerate, so return an Enumerator public static IEnumerable<T> EnumerateRotated<T>(this IList<T> list, int startFrom) { if (list == null) { throw new ArgumentNullException("list"); }

    if (startFrom < 0 || startFrom >= list.Count)
    {
    	throw new ArgumentException("From must be greater 0 and less than the count of the list ("
    		+ list.Count + ", but was " + startFrom,
    		"from");
    }
    
    int lnCount = 0;
    for (int lnIndex = startFrom; lnCount < list.Count; lnIndex = (lnIndex + 1) % list.Count)
    {
    	yield return list[lnIndex];
    	lnCount++;
    }
    

    }

Leave a comment on “Helpful SQL Helpers”

Log In or post as a guest

Replying to comment #:

« Return to Article