Once upon a time, someone wanted to store date ranges in a database. And so, they started down the obvious path of having two columns, one to hold the starting date of the range, and one to hold the ending date. But even going down that route, they tripped and fell, because they ended up with two database fields name Startdate
and StartdateStart
. Startdate
was the end of the period.
You might be thinking, "Well, at least they used the database datetime types," but on that front, you'd be wrong. They used text, and in some cases, instead of Startdate
holding a date, it held a string in the format 22-08-2022 to 27-08-2023
.
Someone had to write code to parse that data, and that someone did the job and then left. Which meant Niels H had to support the resulting C#.
private static void ComputeDates(string Period, ref DateTime Startdate, ref DateTime Enddate)
{
var Temp1 = Period.Split(" to ".ToCharArray());
var Temp2 = Temp1[0].Split('-');
Startdate = new DateTime(int.Parse(Temp2[2]), int.Parse(Temp2[1]), int.Parse(Temp2[0]));
Temp2 = Temp1[4].Split('-');
Enddate = new DateTime(int.Parse(Temp2[2]), int.Parse(Temp2[1]), int.Parse(Temp2[0]));
}
Most of this code is pretty typical bad date handling code. We split the string on " to "
, to give us our dates. Then we split the substrings on "-"
, to get our date parts. Then we construct a datetime out of the results.
Obviously, using the built-in functions would be better. They do all this work for temp variables but then they reuse the same variable to hold different things, which I can't say I love either. But that doesn't rise to a WTF. It's one specific confusing line that gets us there:
Temp2 = Temp1[4].Split('-');
Why a four? The code works, so this is correct, but we split on " to "
, so I'd naturally expect the array to be ["22-08-2022", "27-08-2023"]
.
Except we didn't split on " to "
. We split on " to ".ToCharArray()
. The C# split function is highly overloaded. If you give it a string, it splits on the string. If you give it a character, it splits on the character. If you give it an array of characters, it treats each individual character as a split point.
The resulting array is ["22-08-2022", "", "", "", "27-08-2023"]
.
Converting the split string into an array is such a specific choice, I can only assume that the developer responsible didn't understand the various overloads of Split
, and instead saw it done this way once, and has done it that way ever since. I will even guess that they figured out that 4
was the correct index by trial and error. I have no concrete evidence, but it feels right for this kind of mindless copying.