CodeSOD: Is This Terning Into a Date?
Bad date handling code is like litter: offensive, annoying, but omnipresent. Nobody is specifically responsible for it, nobody wants to clean it up, and we end up ignoring it.
Murtaza K offers up a particularly malodorous example, though, that's worthy of note. It's got everything: string mangling, assumptions that ignore locale, bad ternaries, and it's completely unnecessary.
string Stdt = String.Empty;string FromDt = stDtTime.ToShortDateString();string[] varFromDate = FromDt.Split('/');string mth = Convert.ToInt32(varFromDate[0]) < 10 ? varFromDate[0] : varFromDate[0];string date = Convert.ToInt32(varFromDate[1]) < 10 ? varFromDate[1] : varFromDate[1];FromDate = mth + "/" + date + "/" + varFromDate[2];Stdt = FromDate;
Let's start with "unnecessary". Assuming a US-like locale, or as I like to call it, "middle-endian dates", Stdt will contain what was in FromDt right at the start, rendering all of this pointless. Pointless, anyway, if your goal is to handle dates. But there's so much else special about this, and specifically, I'm talking about those ternaries.
string mth = Convert.ToInt32(varFromDate[0]) < 10 ? varFromDate[0] : varFromDate[0];
I have a hunch about what's going on here. Imagine, if you will, you don't actually know how to write software. What you do know is a vague bit about how to use Visual Studio, and how to search Stack Overflow. Over the years of your career, you haven't really learned anything or gotten better at your job, but you have built an increasingly complex pile of code snippets you've copy/pasted from Stack Overflow. They've mutated as you try and adapt them to new scenarios.
So, what is in varfromDate[0]? Why, a number. I mean, the datatype is string, but you don't understand what that means. You just know it's a number. So you know you need to convert it to a string to do some string concatenation. One of your many snippets was a homework question about converting numbers to strings. The goal was to teach students how to do modular arithmetic to get the ones place, tens place, etc., but the snippet you copied was a bad answer which used individual ternary blocks to pick off individual digits.
You don't know what it is, or what you're doing, but you copy that code in blindly. It doesn't work. You tweak things until it does, and in this case, you return the same value from either branch.
Then you mash the strings back together to make a date. Once it works, you copy/paste it back into the Word document you use for tracking all your "knowledge". You can now reuse this solution in the future.
Do I know that's what happened? Of course not. Is that still probably what happened? Yeah, I think so.
[Advertisement] Forget logs. Next time you're struggling to replicate error, crash and performance issues in your apps - Think Raygun! Installs in minutes. Learn more.