Monday , 27 March 2017
Home » Code You Should Not Be Writing – Part 5

Code You Should Not Be Writing – Part 5

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.

[sourcecode language=”csharp”] 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;
}
[/sourcecode]

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! 🙂

About Justin Lee

Check Also

My experience with the OCBC Cycle Cafe Bike Crawl

A few weeks ago, I had the opportunity to go on a cafe bike crawl …

2 comments

  1. 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 =-.

  2. 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 =-.

Leave a Reply