A Little More Simplified

  • Phill 2007-11-19 09:06
    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text)
    {
    DateTime dateTime;
    return DateTime.TryParse(text, out dateTime);
    }

    Note from Alex: Fixed the article. Go figured, I retyped this one instead of using the submited image. It was early.
  • AppleMunkey 2007-11-19 09:06
    The real WTF is that it's an image? Now I can't copy/paste this genious solution. :-(
  • Cloak 2007-11-19 09:12
    AppleMunkey:
    The real WTF is that it's an image? Now I can't copy/paste this genious solution. :-(


    Hey, I WANTED to do that, too.
  • hallo.amt 2007-11-19 09:13
    I'm sure he meant:

    protected bool checkDateTime(string text)
    {
    //DateTime dateTime;
    return DateTime.TryParse(text, out dateTime);
    }
  • Tom B 2007-11-19 09:14
    I think it should be

    success=DateTime.TryParse(text)
  • Stilgar 2007-11-19 09:14
    Phill:
    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text)
    {
    DateTime dateTime;
    return DateTime.TryParse(text, out dateTime);
    }


    Exactly my thought. Is it some strange home made version of the framework?


    I'm sure he meant:

    protected bool checkDateTime(string text)
    {
    //DateTime dateTime;
    return DateTime.TryParse(text, out dateTime);
    }


    I think it should be

    success=DateTime.TryParse(text)


    Neither would work
  • Nutmeg Programmer 2007-11-19 09:33
    DateTime MyDate;
    if (!DateTime.TryParse(text, MyDate)) MyDate = DefaultDate;
  • tsrtg 2007-11-19 09:52
    To match the original code (and to have consistent conversion on PCs with different locales), he should use TryParseExact with format string and DateTimeFormatInfo.InvariantInfo provider.
  • Tom B 2007-11-19 09:56
    As noted above -- I messed up. I forgot my out reference.
  • Sameer Alibhai 2007-11-19 09:56
    You guys are confusing me, I think I will just stick with the original 100 line solution
  • gabba 2007-11-19 09:57
    Too bad Travis couldn't have somehow worked that nice regex into his solution, though.
  • Bradford 2007-11-19 09:58
    lol wtf bbq were they thinking
  • Crabs 2007-11-19 09:59
    Try{
    return DateTime.Parse(text);
    }Catch{
    throw;
    }

    ..I never liked TryParse...
  • bull 2007-11-19 10:01
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.
  • Stilgar 2007-11-19 10:01
    I finally understood how they managed to compile the fix. They are using C# 3.0 extension methods and have extended upon DateTime with something like

    public static void TryParse(this DateTime dateTime, string s, out bool success)
    {
    DateTime temp;
    success = dateTime.TryParse(s, out temp);
    }

    btw can someone enlighten me on this CAPTHA thing in some peoples posts?
  • Jamie 2007-11-19 10:03
    Crabs:
    Try{
    return DateTime.Parse(text);
    }Catch{
    throw;
    }

    ..I never liked TryParse...


    TRWTF winnah!
  • Phill 2007-11-19 10:03
    Phill:
    Wow - and did Travis try compiling that?

    Maybe he meant:

    protected bool checkDateTime(string text)
    {
    DateTime dateTime;
    return DateTime.TryParse(text, out dateTime);
    }

    Note from Alex: Fixed the article. Go figured, I retyped this one instead of using the submited image. It was early.


    Ok, we'll let you anyway with it!

    This time.
  • Darrell Kress 2007-11-19 10:09
    The WTF is why Travis thinks he is so much smarter then the original programmers, who he feels didn't have command of the DateTime object.

    TryParse was a CLR 2.0 addition, CLR 1.1 had Parse and ParseExact. Since I don't want to go dig out my 1.0 compiler, I can't check if Parse was on the original DateTime object at all.

    I am sure most companies have existing code bases which they stable, tested, retested, validated, and really don't need to be touched when there is much more work to do.

    So congrats on finding a framework way of doing something that was probably written before the framework caught up.


  • mag31 2007-11-19 10:12
    Err, its a checking function. TryParse is the correct solution or:

    bool success;
    try
    {
    DateTime.Parse(text);
    success = true;
    }
    catch
    {
    success = false;
    }

    return success;

    .. which is a little cumbersome.
  • tag 2007-11-19 10:19
    Stilgar:

    btw can someone enlighten me on this CAPTHA thing in some peoples posts?


    Try adding a comment as unregistered user. You will be enlightened.
  • remz 2007-11-19 10:25
    yet another I-don't-bother-looking-for-a-working-existing solution-and-write-my-own wtf.
  • m0ffx 2007-11-19 10:28
    If WTFs were to be disqualified on grounds of too common (like Darwin Awards are), then re-inventing the square date processing wheel would probably be the first to be thusly disallowed.
  • PeriSoft 2007-11-19 10:29
    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.
  • Sad Bug Killer 2007-11-19 10:47
    This site is getting worse (not necessarily in the right chronological order) with time:
    1) first some inappropriate ads spawned (flashing images at the end of posts)
    2) then the number of ads increased
    3) then Error'd articles started to prevail
    4) then the name changed
    5) then a screenshot of source code appeared (someone please add a nice wood texture to the image)

    At first I was thinking of posting what do I expect in the future, but I won't. And yes, I know you don't care what I think of the site and its development, I just wanted to rant pointlessly for a while. This warm and fuzzy feeling I had about this site is going away, I feel like I'm losing a friend here.

    And next time post JPEG screenshot of the source so that we can at least mock you in full
  • Tei 2007-11-19 10:49


    the captcha thing. is a meme created on this site.

    long version:

    the source is this: the forum software of this site used to be very bad, and with very bad, i mean a giganteous pieze of WTFery, whas HARD to post something. so the words "The Real WTF is the forum software" used to be very true. the addition of a captcha whas also a joke, as the rest of the site. so people started complaining adding his captchas for no reason.
    but because the set of text on the captcha where on-topic, people started adding then.. because fit the current post.

    after changes, updates, etc... we have a forum good enough, so is no more needed, most people still use it, as people love memes, but is still some lame.

    short version:
    is some sort of fortune cookie.
  • Anonymouse 2007-11-19 10:49
    This is probably just some old code dating back to before the .net implementation. And really, if it's an isolated function, it's fast enough, and it does what you want it to, leave the poor function alone.
  • blirp 2007-11-19 10:52
    After all that nice and fun RegEx to validate input, the code then parses with String.Split()? What's wrong with RegEx.Split()?
    And what's up with the 'month-day-year'-format? Does anybody actually use that? In 2007? It's as archaic as feet and inches... </sarcasm>

    M.

    Captcha: muhahaha
  • Mad Time Traveller 2007-11-19 10:53
    The more I see code that handles dates and times, the more I think using decimal time or at least metric time would have more good than bad side effects. They actually tried to implement decimal time after the French Revolution, but unfortunately we didn't stick with it.

    This is also a good idea.

    The big problem (as it usually is in programming) is the legacy.
  • Zylon 2007-11-19 11:41
    Stilgar:
    btw can someone enlighten me on this CAPTHA thing in some peoples posts?


    It's an intelligence test for unregistered users. If they post their CAPTCHA, they fail.
  • Chris G 2007-11-19 11:42
    Geez, never use a try { } catch { }, do you know the overhead in using one of those?
  • Try Catch 2007-11-19 11:46
    And the real WTF is:

    Chris G:
    never use a try { } catch { }


    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.
  • Shial 2007-11-19 11:47
    PeriSoft:
    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.


    Or they could all be right. Code is more like an art form than an exact science. Just like art as well everybody is positive that they have the masterpiece and everybody else are just posers(or their genuis is just misunderstood). You can have multiple solutions and all can come up with the same answer.
  • -j 2007-11-19 11:48
    Mad Time Traveller:
    The more I see code that handles dates and times, the more I think using decimal time or at least metric time would have more good than bad side effects. They actually tried to implement decimal time after the French Revolution, but unfortunately we didn't stick with it.


    The revolution introduced the "10 day week" with only one day a week off, so exposing the essentially bourgois nature of the French revolution.

    As to you main point, Unix time gives 1 second resolution from 1970-2037 on 32 bit hardware, 1970-the-end-of-time on 64 bit. What could be easier!
  • moose 2007-11-19 11:51
    Try Catch:
    And the real WTF is:

    Chris G:
    never use a try { } catch { }


    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.


    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...
  • Reflector 2007-11-19 12:12
    internal static unsafe bool TryParse(string s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result)
    {
    DateTime time;
    if (s == null)
    {
    result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s");
    return false;
    }
    if (s.Length == 0)
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    DS bEGIN = DS.BEGIN;
    bool flag = false;
    DateTimeToken dtok = new DateTimeToken {
    suffix = TokenType.SEP_Unk
    };
    DateTimeRawInfo raw = new DateTimeRawInfo();
    int* numberBuffer = stackalloc int[3];
    raw.Init(numberBuffer);
    result.calendar = dtfi.Calendar;
    result.era = 0;
    __DTString str = new __DTString(s, dtfi);
    str.GetNext();
    do
    {
    if (!Lex(bEGIN, ref str, ref dtok, ref raw, ref result, ref dtfi))
    {
    return false;
    }
    if (dtok.dtt != DTT.Unk)
    {
    if (dtok.suffix != TokenType.SEP_Unk)
    {
    if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok))
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    dtok.suffix = TokenType.SEP_Unk;
    }
    if (dtok.dtt == DTT.NumLocalTimeMark)
    {
    switch (bEGIN)
    {
    case DS.D_YNd:
    case DS.D_YN:
    return ParseISO8601(ref raw, ref str, styles, ref result);
    }
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    bEGIN = dateParsingStates[(int) bEGIN][(int) dtok.dtt];
    if (bEGIN == DS.ERROR)
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    if (bEGIN > DS.ERROR)
    {
    if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != DateTimeFormatFlags.None)
    {
    if (!ProcessHebrewTerminalState(bEGIN, ref result, ref styles, ref raw, dtfi))
    {
    return false;
    }
    }
    else if (!ProcessTerminaltState(bEGIN, ref result, ref styles, ref raw, dtfi))
    {
    return false;
    }
    flag = true;
    bEGIN = DS.BEGIN;
    }
    }
    }
    while (((dtok.dtt != DTT.End) && (dtok.dtt != DTT.NumEnd)) && (dtok.dtt != DTT.MonthEnd));
    if (!flag)
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    AdjustTimeMark(dtfi, ref raw);
    if (!AdjustHour(ref result.Hour, raw.timeMark))
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
    return false;
    }
    bool bTimeOnly = ((result.Year == -1) && (result.Month == -1)) && (result.Day == -1);
    if (!CheckDefaultDateTime(ref result, ref result.calendar, styles))
    {
    return false;
    }
    if (!result.calendar.TryToDateTime(result.Year, result.Month, result.Day, result.Hour, result.Minute, result.Second, 0, result.era, out time))
    {
    result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
    return false;
    }
    if (raw.fraction > 0.0)
    {
    time = time.AddTicks((long) Math.Round((double) (raw.fraction * 10000000.0)));
    }
    if ((raw.dayOfWeek != -1) && (raw.dayOfWeek != result.calendar.GetDayOfWeek(time)))
    {
    result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
    return false;
    }
    result.parsedDate = time;
    if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly))
    {
    return false;
    }
    return true;
    }
  • Richard 2007-11-19 12:27
    Travis messed up. The original code knew that there are 99 days in February (except in leap years, when there are 28). People like myself born on 02/99/1983 were quite happy with the old code, but sorely disappointed by Travis' "rewrite".
  • john 2007-11-19 12:28
    seriously, this is a challenge!
    Implement a DateTime validating routine in compact framework 2.0 for windows mobile 5.0, without using regexp, nor exception catching. Input a string, output is a boolean which will tell whither DateTime.Parse with thow an exception or not if you would feed it with the same string (good testcase uh?)

    A beer to the winner
    //John
  • Try Catch 2007-11-19 13:21
    moose:
    Try Catch:
    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.


    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...


    WOW!

    Then the real WTF if the implementation of exceptions in .NET (I read the article which states that "exception handling is very slow"). This kind of defeats the purpose of having exceptions, since you're going to start rewriting functions the old way to go around the bad performance of the implementation...
  • Mike 2007-11-19 13:23
    I'm not really sure what the WTF here is. Assuming it's code from before the 2.0 framework, this is a quick way of doing things. Sure, you can catch the exception on DateTime.Parse, but if you're doing this for lots of dates, this isn't going to be particularly fast.

    Also, isn't the new implementation culture sensitive whereas the old one wasn't? The new solution could cause more headaches than it fixes ...
  • Tei 2007-11-19 13:29
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow?
    fix the damn old implementation!
  • Stilgar 2007-11-19 13:57
    Tei:


    the captcha thing. is a meme created on this site.

    long version:

    the source is this: the forum software of this site used to be very bad, and with very bad, i mean a giganteous pieze of WTFery, whas HARD to post something. so the words "The Real WTF is the forum software" used to be very true. the addition of a captcha whas also a joke, as the rest of the site. so people started complaining adding his captchas for no reason.
    but because the set of text on the captcha where on-topic, people started adding then.. because fit the current post.

    after changes, updates, etc... we have a forum good enough, so is no more needed, most people still use it, as people love memes, but is still some lame.

    short version:
    is some sort of fortune cookie.


    10x for the explaination

    and to all the others: I know what captcha is. I just didn't know why so many people put it on the end of their posts.

    CAPTCHA: pointer
  • Anonymous 2007-11-19 14:32
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.
  • Paul 2007-11-19 14:34
    Tei:
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow?
    fix the damn old implementation!


    I don't do .NET, but 30 seconds of digging shows me that TryParse has a different signature to Parse - it returns a boolean and you pass in the variable to hold the result, whereas Parse returns the result. It seems to me (after pondering this for all of 15 seconds) that you can't do what TryParse does with the Parse signature.

    And I'm pretty sure that Parse will have been optimized if possible ... the issue is that it can throw an Exception if the input is invalid, and catching an Exception is slow, apparently. You can't change the behaviour of Parse if it's possible you'll break existing apps, so they created a new method. (The name TryParse ... now that's a wtf)
  • Fabian 2007-11-19 14:40
    Richard:
    Travis messed up. The original code knew that there are 99 days in February (except in leap years, when there are 28). People like myself born on 02/99/1983 were quite happy with the old code, but sorely disappointed by Travis' "rewrite".


    Quite. If this is an actual screen shot of the original code, that "else if" is one level off.

    I was also slightly surprised to see the check for February happen before the check on 30-day months... I always try to check for the most obvious first. Am I wrong in doing this?

    Fabian
    PS: 1983? Seriously? I'm getting old... :-|
  • Stilgar 2007-11-19 14:41
    How is the name a WTF? That is exactly what the method does. CanParse would be unappropriate because TryParse not only checks if parsing is possible but does parse the input. BTW this naming convention is consistent through .NET.

    try/catch is not only slower (usually you don't care that much about speed) but also a more complicated construct. if is always better than try/catch
  • Holy Roller 2007-11-19 15:17
    Zylon:
    Stilgar:
    btw can someone enlighten me on this CAPTHA thing in some peoples posts?


    It's an intelligence test for unregistered users. If they post their CAPTCHA, they fail.


    It's actually a sign to others who are not stupid enough to register on any page as a user.

    CAPTCHA: howdy - howdy do dat?
  • swordfishBob 2007-11-19 15:26
    Didn't anyone notice: day and month are the wrong way around.
  • Hey 2007-11-19 15:49
    The real wtf here is that they used .net.

    Captcha: crapper
  • Matt 2007-11-19 16:19
    Had a similar issue at my job, some guy wrote a Perl module to handle date parsing, rewrote 1,000 lines of horrible Perl in about 2 lines of good perl.
  • Simon 2007-11-19 16:41
    DateTime.Parse has always been in the framework.

    In 2.0 convenience methods like TryParse were added because MS realised that everyone rolled their own, and the bool TryXXX( something, out realObject) pattern was added to standardise things a bit.

    One wonders what codebase really wants to use their own homegrown datetime code. Back in the day, these were usually done because the built-in library calls were insufficient. Homegrown approaches almost always have some sort of bug or limitation.

    It just sounds like you're advocating laziness under the banner of 'it worked when I copied it out of our old C codebase, and there surely can't be anything wrong with it'. phooey!

    In any event, replacing a few dozen lines with just 2 is productive. Less code is more (it's called refactoring) and I'm sure if you re-run the unit tests it'll quickly find if there are any bugs in the old code.

    In conclusion, don't rewrite the framework, because the people who wrote the framework are probably a lot smarter than you.
  • Anonymous 2 2007-11-19 17:01
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.
  • Anonymous 2007-11-19 17:10
    Anonymous 2:
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.

    Whatever they write in, I'm sure they don't go from forum to forum bitching "DURR COMPUTER PROGRAMMING IS HARD DURR BUT I WANT TO BE A PROGRAMMER DURR". Unluckily for the rest of the people Microsoft and other companies found great ways to produce coding monkeys that are so fond of their handy dandy languages that they don't really know what's happening. (that last statement is a little bit derogatory to the monkeys)
  • simplicity 2007-11-19 17:11
    Simon:

    In conclusion, don't rewrite the framework, because the people who wrote the framework are probably a lot smarter than you.


    So, so true.
  • Paul 2007-11-19 17:51
    Anonymous 2:
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.


    Real programmers design their coding languages, and install their programs on self-built computers using dip switches.
  • Greg Poole 2007-11-19 17:56
    Whoa whoa whoa guys, is it just me or is the real WTF here using Char.Parse to get the characters for the split function?
  • Sigivald 2007-11-19 18:07
    Us VB.NET people would just use IsDate(date) anyway.

    TryParse? Scoff.

  • centuryBeforeLast 2007-11-19 18:07
    the new code probably does not fulfill all requirements of the old: The check for dates before 1900 is missing. I am not sure if this check was really part of the original requirements or why it was there in the first place, but I guess .NET does not have the exact same requirement built-in
  • real_aardvark 2007-11-19 18:42
    moose:
    Try Catch:
    And the real WTF is:

    Chris G:
    never use a try { } catch { }


    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.


    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...

    That is quite the saddest thing I have ever read on this site. Including things that I have written.

    "Hoo" is this "u" to whom "euuurghhh..", sorry, "u" refer?
  • .net hater 2007-11-19 19:27
    Oh really, try generating a graphic on the screen by pixel. No nice picturebox with pset.
  • meh 2007-11-19 20:10
    And what if they wanted to mandate particular date format?

    Isn't .Net's function trying to be smart, locale-dependent, etc? If so, I wouldn't rely on that (change of system language breaks dates? Ugh, that's WTF!)
  • Anon 2007-11-19 23:57
    Darrell Kress:
    The WTF is why Travis thinks he is so much smarter then the original programmers, who he feels didn't have command of the DateTime object.

    TryParse was a CLR 2.0 addition, CLR 1.1 had Parse and ParseExact. Since I don't want to go dig out my 1.0 compiler, I can't check if Parse was on the original DateTime object at all.

    I am sure most companies have existing code bases which they stable, tested, retested, validated, and really don't need to be touched when there is much more work to do.

    So congrats on finding a framework way of doing something that was probably written before the framework caught up.


    You don't need your old compiler, MSDN clearly lists DateTime.Parse as 1.0 compatible. Since the code is written in C# there's really no excuse for having crap like this in your code base, unless it's some kind of automated port. Even then, manually refactoring is rarely a waste of time if you can get rid of huge chunks of cryptic crap that has no comments and is using RegEx's to boot.

    protected bool CheckDateTime(string dateTime)
    {
    try
    {
    DateTime.Parse(dateTime);

    return true;
    }
    catch
    {
    return false;
    }
    }

    ... is 1.0 compatible.

    Chris G:
    Geez, never use a try { } catch { }, do you know the overhead in using one of those?


    Never? Are you serious? Do you know the overhead in maintaining code that deliberately departs from the simple and obvious? Write a few lines of code, write a comment, and move on. Unless you're programming the navigation software for the next mission to Mars, the overhead of try/catch is not a conversation 99% of programmers would ever need to waste time on.
  • Phlip 2007-11-20 02:54
    I see that the "Char.Parse()" calls and the misplaced else in February (which I'd call a dangling else if it wasn't for those explicit braces in there) have already been mentioned...

    There's also the
    if ((mon == 1 || mon == 3 || ...) && day < 1 || day > 31)
    line, which looks broken due to the order of operations (&& groups tighter than ||) but, by luck, the code will actually still work (of course, if the same bug was on the check for the 30-day months, it'd fail).

    Also, matching the string with a regex, but not using captures within that regex, and then parsing it by hand.

    I was also about to mention the overelaborate way of building chr[], but then I remembered, this is C#, not C++... I guess cstrings aren't available?
  • Ivory Tower 2007-11-20 04:37
    Anonymous:
    Anonymous 2:
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.

    Whatever they write in, I'm sure they don't go from forum to forum bitching "DURR COMPUTER PROGRAMMING IS HARD DURR BUT I WANT TO BE A PROGRAMMER DURR". Unluckily for the rest of the people Microsoft and other companies found great ways to produce coding monkeys that are so fond of their handy dandy languages that they don't really know what's happening. (that last statement is a little bit derogatory to the monkeys)
    No, of course, real programmers never use any pre-built packages -- they always code everything starting with bare metal. That's why they are so productive, generating whole programs in mere years.

    Then, of course, they go from forum to forum bitching that everyone in the world is dumber than them.
  • AnonCoder 2007-11-20 05:25
    moose:
    Try Catch:
    And the real WTF is:

    Chris G:
    never use a try { } catch { }


    Not even when it's the right thing to do? I mean, exceptions are there for a reason, aren't they?

    Anyway, how do you think the TryParse() function works? I pretty much doubt that the internal implementation is anything that doesn't call Parse() in a try/catch block.


    It isnt just Parse wrapped, it is quite a bit quicker. Google if u want the story why it was implemented...


    Yeah, let's save a few clock cycles at the expense of writing far less maintainable code. That's economical.

    Unless you're developing apps that are CPU bottlenecked, where response time is critical, AND are parsing vast numbers of datetimes of which a significant proportion are invalid then using TryParse is utterly pointless.

    The reality is that when you're parsing input like this you're almost never going to be CPU bound, so just parse the damn thing and catch the exception, it makes for much clearer and cleaner code and you won't get shot in the face by a maintenance developer a year from now.
  • James 2007-11-20 05:28
    Ivory Tower:
    Anonymous:
    Anonymous 2:
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.

    Whatever they write in, I'm sure they don't go from forum to forum bitching "DURR COMPUTER PROGRAMMING IS HARD DURR BUT I WANT TO BE A PROGRAMMER DURR". Unluckily for the rest of the people Microsoft and other companies found great ways to produce coding monkeys that are so fond of their handy dandy languages that they don't really know what's happening. (that last statement is a little bit derogatory to the monkeys)
    No, of course, real programmers never use any pre-built packages -- they always code everything starting with bare metal. That's why they are so productive, generating whole programs in mere years.

    Then, of course, they go from forum to forum bitching that everyone in the world is dumber than them.


    Everyone in the world IS dumber than me. Still, I like to be productive.

    Here's a nice example showing the performance gains from using TryParse. http://blogs.msdn.com/ianhu/archive/2005/12/19/505702.aspx

  • Phill 2007-11-20 06:12
    AnonCoder:

    Yeah, let's save a few clock cycles at the expense of writing far less maintainable code. That's economical.

    Unless you're developing apps that are CPU bottlenecked, where response time is critical, AND are parsing vast numbers of datetimes of which a significant proportion are invalid then using TryParse is utterly pointless.

    The reality is that when you're parsing input like this you're almost never going to be CPU bound, so just parse the damn thing and catch the exception, it makes for much clearer and cleaner code and you won't get shot in the face by a maintenance developer a year from now.


    WTF? Are you seriously saying that TryParse is in any way unmaintainable? The least that you can expect from future maintainers of your code is that they know how to program and have read an API or two in their lives.
    Using Parse and unneccessarily catching an exception is not good practice. Exceptions are supposed to be exceptional. Sometimes, it would be exceptional for the parse to fail so use Parse and handle the exception appropriately and sometimes, it is likely that the parse will fail (for any number of reasons) so use TryParse and write much cleaner code.
    I'm not concerned about the performance of exceptions here as I don't think it applies in most cases (as you pointed out).
  • Iceman 2007-11-20 06:20
    Stilgar:
    How is the name a WTF? That is exactly what the method does. CanParse would be unappropriate because TryParse not only checks if parsing is possible but does parse the input. BTW this naming convention is consistent through .NET.

    try/catch is not only slower (usually you don't care that much about speed) but also a more complicated construct. if is always better than try/catch


    It obviously should have been call TryParseCatchEndTry, at least for the VB.Net guys here :-)
  • AnonCoder 2007-11-20 06:49
    Phill:

    WTF? Are you seriously saying that TryParse is in any way unmaintainable? The least that you can expect from future maintainers of your code is that they know how to program and have read an API or two in their lives.
    Using Parse and unneccessarily catching an exception is not good practice. Exceptions are supposed to be exceptional. Sometimes, it would be exceptional for the parse to fail so use Parse and handle the exception appropriately and sometimes, it is likely that the parse will fail (for any number of reasons) so use TryParse and write much cleaner code.
    I'm not concerned about the performance of exceptions here as I don't think it applies in most cases (as you pointed out).

    I'm not a .NET dev myself so forgive me if I'm missing something about the platform but I would have thought that the concepts of maintainable code transferred pretty well.

    I'm saying that using "If" over try/catch leads to code that is less well factored and hence less maintainable.

    Ignoring the clock cycles we both agree don't need saving - what's the difference between my unnecessary "catch" and your unnecessary "else"?

    My input error handling code is nicely separated from the rest without many levels of nesting, it handles errors from attempts to parse all 8 dates in the BookingObject or whatever consistently and I have a nice "finally" block to cleanup any resources I might want to (.NET does have finally right?).
  • Dave 2007-11-20 06:58
    Gawd, reminds me of this hacked together VB6 timesheet system I had to extend. Not only did it do all the math manually instead of using the standard functions it had a ton of functions to do the same thing (half of it inline where it was needed instead of in separate functions), but slight differences (some versions taking leap years into account, others not doing, etc).

    Kept wanting to rewrite or otherwise replace the thing but kept getting turned down but must have spent over a hundred hours over a few years making all kinds of changes that were requested and fixing bugs.
  • brazzy 2007-11-20 10:28
    Try Catch:
    Then the real WTF if the implementation of exceptions in .NET (I read the article which states that "exception handling is very slow"). This kind of defeats the purpose of having exceptions, since you're going to start rewriting functions the old way to go around the bad performance of the implementation...

    Oh dear.
    It does NOT defeat the purpose of having exceptions since exceptions are, as the name indicates, supposed to be used for exceptional circumstances i.e. rarely, and something that only happens rarely cannot really cause bad performance.

    So unless you are misusing exceptions for non-exceptional things or doing premature optimization, there is no problem.
  • brazzy 2007-11-20 10:41
    -j:
    Mad Time Traveller:
    The more I see code that handles dates and times, the more I think using decimal time or at least metric time would have more good than bad side effects. They actually tried to implement decimal time after the French Revolution, but unfortunately we didn't stick with it.


    The revolution introduced the "10 day week" with only one day a week off, so exposing the essentially bourgois nature of the French revolution.

    They were also planning to divide the day into 10 hours of 100 minutes containing 100 seconds each (would have made the second only about 15% shorter), but never implemented it because replacing all clocks would have been to expensive.

    As to you main point, Unix time gives 1 second resolution from 1970-2037 on 32 bit hardware, 1970-the-end-of-time on 64 bit. What could be easier!

    Nothing, if you didn't have to convert to and from human-readable formats all the time. As it is, this conversion is extremely complex and failure-prone. It would be much simpler if you had only one disparate factor rather than half a dozen or more. Too bad the earth's orbit length isn't a nice round multiple of its day length.
  • AdT 2007-11-20 11:07
    I never thought I'd end up defending a WTF, but the replacement code does not do the same thing as the original code. This might be a good or a bad thing depending on context, but it's a fact. For one, the original code is culture invariant and always expects dates to be in a specific format (ISTM en-US) and in accordance with the Gregorian calendar. Even if the TryParse, which is called without specifying a CultureInfo object, could be assumed to always accept dates in the given format, TryParse will also accept dates in other formats (and possibly calendars, e.g. Islamic) depending on the CurrentCulture. Some might be surprised to learn that there are cultures other than en-US.

    So TryParse would return true where the original code returns false. If this was an actual parsing method, this might be benign. But since this can be used for validation, and the actual parsing might be done somewhere further down the line, this can be dangerous or at least annoying. A simple example: This method might be used to validate value dates entered into a system. The transactions are then passed on to an accounting system but the accounting system might not accept the dates in this format, yielding an error.

    All that said, the method is still excessively verbose. The same functionality could be achieved by combining a call to TryParse with a suitable CultureInfo object && Regex.IsMatch if necessary. That might increase the LOCs for the replacement from 2 to 3 or 4, but that would still be no match for the original implementation.
  • FredSaw 2007-11-20 11:19
    PeriSoft:
    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.
    In a multitude of counselors there is wisdom. - Proverbs 11:14

    Look at it this way: they will keep hacking at it, and at each other's work, until they get it right. Then 30 developers will go away educated and enlightened, and they will have had fun in the process. The disdain you see comes across that way due to the nature of the internet, which doesn't allow for facial expression or vocal inflection. Think of it as being like neighborhood pals playing some weekend football in their front yards and shouting friendly insults at each other in the typical male one-upmanship routine.
  • Ragnax 2007-11-20 12:33
    meh:
    And what if they wanted to mandate particular date format?

    Isn't .Net's function trying to be smart, locale-dependent, etc? If so, I wouldn't rely on that (change of system language breaks dates? Ugh, that's WTF!)


    And this is why stuff like this exists:

    public void SetCulture(string cultureUID)
    
    {
    Thread.CurrentThread.CurrentCulture =
    Thread.CurrentThread.CurrentUICulture =
    CultureInfo.CreateSpecificCulture(cultureUID);
    }


    Voila! Force your application to run in the locale you're expecting, if you really need it to.

    Ofcourse, you could also build a customized DateTimeFormatProvider and pass that to the DateTime parsing methods if that's the only localized feature of the framework you want to force to a specific format.
  • AdT 2007-11-20 12:50
    Ragnax:
    Ofcourse, you could also build a customized DateTimeFormatProvider and pass that to the DateTime parsing methods if that's the only localized feature of the framework you want to force to a specific format.


    Or you could just pass the desired CultureInfo's DateTimeFormat to DateTime.TryParse. That would be too easy, though.
  • Government Wonk #37 2007-11-20 18:09
    We have some $45 million consultants to the same, except when they did DaysInMonth the remembered the poem "30 days hath September, April, May, and November." (read it carefully...one of these things does not belong...).
  • Jim 2007-11-21 06:22
    Paul:
    Tei:
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow?
    fix the damn old implementation!


    I don't do .NET, but 30 seconds of digging shows me that TryParse has a different signature to Parse - it returns a boolean and you pass in the variable to hold the result, whereas Parse returns the result. It seems to me (after pondering this for all of 15 seconds) that you can't do what TryParse does with the Parse signature.

    And I'm pretty sure that Parse will have been optimized if possible ... the issue is that it can throw an Exception if the input is invalid, and catching an Exception is slow, apparently. You can't change the behaviour of Parse if it's possible you'll break existing apps, so they created a new method. (The name TryParse ... now that's a wtf)


    Good that you are not a .NET programmer
  • b1xml2 2007-11-21 08:50
    That's not the WTF. The WTF is smart alecks like yourself who think that code written in .NET 1.x when ported to .NET 2.0 should not be refactored.

    If I saw such code, I would have outed the people who wrote it or those who ported it. Even in .NET 1.x, one could use the ParseExact. Parse has always been on the DateTime object since 1.0.
  • Reinier 2007-11-21 10:35
    I find myself using the following pattern in a lot of code:

    bool Action(sometype argument, bool reallyDoIt)

    The boolean argument tells the function whether to actually proceed, should
    the action be possible; the boolean result tells the caller whether the
    action was possible. This is for cases where testing whether the action is possible requires the same code as actually doing it, except that testing bails out as soon as it notices a problem.

    It's not very elegant but I haven't found a better general pattern yet.
  • Anonymous 2007-11-21 12:03
    Ivory Tower:
    Anonymous:
    Anonymous 2:
    Anonymous:
    bull:
    He's most likely a C++ immigrant.
    That's why I love .NET, everything is stupidly simple.

    And it makes YOU stupidly simple, wuss.


    Agreed -- real programmers write bytecode.

    Whatever they write in, I'm sure they don't go from forum to forum bitching "DURR COMPUTER PROGRAMMING IS HARD DURR BUT I WANT TO BE A PROGRAMMER DURR". Unluckily for the rest of the people Microsoft and other companies found great ways to produce coding monkeys that are so fond of their handy dandy languages that they don't really know what's happening. (that last statement is a little bit derogatory to the monkeys)
    No, of course, real programmers never use any pre-built packages -- they always code everything starting with bare metal. That's why they are so productive, generating whole programs in mere years.

    Then, of course, they go from forum to forum bitching that everyone in the world is dumber than them.

    I never suggested they should code everything by hand. If you're a programmer, you're supposed to know how all of this works, not just know that "you input this string and this string and you get that output". Of course learning how all this works is too much for all the tards who want their plaque of a computer engineer, so they just go the simplest way possible. That's why we have shitty games requiring you to upgrade your computer every month to get the best out of it. It's because programming is becoming slightly more intellectual effort than banging your head on the keyboard. The shortcuts (ie libraries that are ready to use) were designed for people who already know what to do, but in the end we get people that wouldn't know how to do shit if they couldn't work with their precious frameworks and IDEs.
  • no u 2007-11-22 05:09
    Richard:
    Travis messed up. The original code knew that there are 99 days in February (except in leap years, when there are 28). People like myself born on 02/99/1983 were quite happy with the old code, but sorely disappointed by Travis' "rewrite".


    Silly you, there's only 12 months on a year, not 99.
  • Arioch 2007-11-22 10:51
    probably he just did a fast convertion of old codebase into hi-buzz super-nova .Net

    and then "don't fix what is not broken" is quite a good path, if you realy do need a fast conversion, rather than rewriting app from scratch :-)
  • tgfcoder 2007-11-23 05:50
    This is why we don't re-invent the wheel, I gather.. :P
  • Tom_fan_DK 2007-11-23 06:59
    PeriSoft:
    It's funny how in almost every code WTF, 30 people will post their own answers - and each claim to be correct while the other 29 are incorrect.

    Therefore, despite the smug, sanctimonious attitude of the WTFers, the vast majority are, by necessity, wrong.

    As a non-IT person, it does not give me great confidence in IT when a huge community of people who get together to express disdain for unskilled developers cannot agree on how to validate a date input.


    1 - Everyone can answer here, professionals and amateurs, so you're mixing apples with oranges.
    2 - The same task can be accomplished in many different ways, depending on the context. The less you know, the more clear you see the solutions (does it sounds good to you?)
    3 - I'm sure that if I start to look into a website showing errors of accountants (and not beeing accountant myself, that's why I wouldn't understand all the options for the same task)... Do you ensure me that I'll find less incongruences? ;-)
  • Bubba 2007-11-27 02:43
    Reinier:
    I find myself using the following pattern in a lot of code:

    bool Action(sometype argument, bool reallyDoIt)

    The boolean argument tells the function whether to actually proceed, should
    the action be possible; the boolean result tells the caller whether the
    action was possible. This is for cases where testing whether the action is possible requires the same code as actually doing it, except that testing bails out as soon as it notices a problem.

    It's not very elegant but I haven't found a better general pattern yet.


    Isn't it more straightforward to avoid calling a function if it may not do something? You realize that _somewhere_ in each function you apply this pattern to there's a line to the effect of: "if(reallyDoIt) { ...[Actually do something]... }".

    It seems a little more sane to me to do this:
    if( ActionIsSafe(argument) ) { Action(argument); }

    If you really have that many places where you don't know if the code is safe to run until you've run it, you might consider reevaluating most of it.
  • cparker 2007-11-27 11:07
    I did something similar recently, in a JavaScript library.

    Original:
     function check7Days( formfromDate, formtoDate )
    
    {
    var toDate = new Date( formtoDate );
    var fromDate = new Date( formfromDate );

    if ( !fromErr )
    {
    var toMonth = toDate.getMonth() + 1;
    var toDay = toDate.getDate();
    var toYear = toDate.getFullYear();
    var fromMonth = fromDate.getMonth() + 1;
    var fromDay = fromDate.getDate();
    var fromYear = fromDate.getFullYear();

    if ( fromYear == toYear )
    {
    if ( ( fromMonth + 1 ) < toMonth )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    }
    else if ( fromMonth == toMonth )
    {
    if ((fromDay + 7) < toDay)
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if
    }
    // Check if current month equals 30 days
    else if ((fromMonth=='04') || (fromMonth=='06') || (fromMonth=='09') || (fromMonth=='11'))
    {
    // Check if date diff. between Months is not greater than 7 days
    if ( ((toDay+30)-fromDay) > 7 )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if
    } // end if 30 days in a month
    // Check if current month equals 31 days
    else if ((fromMonth=='01') || (fromMonth=='03') || (fromMonth=='05') || (fromMonth=='07') || (fromMonth=='08') || (fromMonth=='10') || (fromMonth=='12'))
    {
    // Check if date diff. between Months is not greater than 7 days
    if ( ((toDay+31)-fromDay) > 7 )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if
    } // end else 31 days calc
    // Check if current year use 28 days in February
    else if (isLeapYear(fromYear))
    {
    // Check if date diff. between Months is not greater than 7 days
    if ( ((toDay+29)-fromDay) > 7 )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if 29 Days in Feb
    } // end else 28 days in February
    else if (!isLeapYear(fromYear))
    {
    if ( ((toDay+28)-fromDay) > 7 )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if 28 Days in Feb
    } // end if
    } // end if
    // if dates difference more than 7 days apart
    else if ( (fromYear+1) == toYear )
    {
    // Check if prior year month is less than Dec
    if ( (fromMonth < 12) || (toMonth > 1) )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if
    else if ( (fromMonth == 12) && (toMonth == 1) )
    {
    if ( ((toDay+31)-fromDay) > 7 )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end if
    } // end else
    }
    else if ( (fromYear+1) < toYear )
    {
    alert( "Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    return( false )
    } // end else
    }
    else
    {
    toErr =true;
    return( false );
    }
    return( true );
    }


    Simplified:
    var fromErr, toErr;
    

    fromErr = toErr = false;

    function check7Days(formfromDate, formtoDate)
    {
    if (!fromErr && new Date(formtoDate) - new Date(formfromDate) > (7 * 24 * 60 * 60 * 1000)) // Date arithmetic is done in milliseconds.
    {
    alert("Date ranges must be submitted in increments of seven calendar days.")
    toErr = true;
    }

    return (!fromErr && !toErr);
    }


    The library that contains the original code is included in each and every page as part of a series of enterprise applications used by thousands of people around the world. Forget P2P; think of all the bandwidth bad code like this uses up! This is just one function in one library among many.

    Let's not forget that this code isn't ready for i18n/L10n... None of it is, despite that most of this company's clients don't speak English as a frist language. When I brought up the idea of i18n with some decision-makers here, they looked dumbfounded (why would we want to do that?) or shocked (we can do stuff like that?).

    Amazing...
  • good 2007-11-27 20:16
    Tei:
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow?
    fix the damn old implementation!
  • good 2007-11-27 20:16
    Tei:
    TryParse... WTF???

    this sound to me like a total languaje WTF, adding a library option that doest nothing new, but is because the old implementation is slow?
    fix the damn old implementation!