This is my last post of the year, and I hope to make it special by giving you a piece of code that just amazes me. Staying within the whole “new year” feel, this code is for validating a date.

string strMessage = string.Empty;
int index = 0;
bool IsInputValid = true;

string strDate = TextBox_Date.Text; // TextBox_Date is just a textbox to get the date from.
DateTime date;
if (strDate.Length == 10)
{
    int year = Int32.Parse(strDate.Substring(6, 4));
    if ((year > 1900) && (year < 3000))
    {
        string strMonth = strDate.Substring(3, 2);
        string strDay = strDate.Substring(0, 2);
        date = Convert.ToDateTime(strMonth + "-" + strDay + "-" + strDate.Substring(6, 4));
    }
    else
    {
        index++;
        strMessage += index + ". Date format(dd/mm/yyyy) is not correct.<br/>";
        IsInputValid = false;
    }
}
else
{
    index++;
    strMessage += index + ". Date format(dd/mm/yyyy) is not correct.<br/>";
    IsInputValid = false;
}

Remember the code you saw in Part 2 about the try-catch, using exceptions to do your data validation? Yes, that code surrounds this code. Imagine the double whammy I got when I saw this code, and the satisfaction of deleting it all.

I don’t know if you realise this, but do you have to take time to actually try to figure out what this developer is trying to do? As in understanding the code? How long do you take to figure out this code and what it is doing, and how flawed it is?

I hope you enjoy this edition of Code You Should Not Be Writing. Till next year, I have more to share! :)

Related posts:

  1. Code You Should Not Be Writing – Part 2
  2. Code You Should Not Be Writing – Part 4
  3. Code You Should Not Be Writing – Part 3
  4. Code You Should Not Be Writing – Part 1
  5. Creating Beautiful Code with Functional Languages
  • http://thinkingnectar.com Chin Yong

    I do not know about you, but the index++ lines makes me laugh.
    .-= Chin Yong´s last blog ..MySQL: Quick Create of User and Database of Same Name =-.

  • http://blog.dk.sg DK

    Are you sure he is trying to do date validation? It doesn’t seem so leh. Looks more like he is trying to create another millennium bug.
    .-= DK´s last blog ..Best of 2009 =-.

   
© 2009 - 2011 JustinLee.sg Suffusion theme by Sayontan Sinha
Stop SOPA!

SOPA breaks our internet freedom!
Any site can be shut down whether or not we've done anything wrong.

Stop SOPA!