CodeSOD: A Step too Var
Astor works for a company that provides software for research surveys. Someone needed a method to return a single control object from a list of control objects, so they wrote this C# code:
private ResearchControl GetResearchControlFromListOfResearchControls(int theIndex, List<ResearchControl> researchControls){ var result = new ResearchControl(); result = researchControls[theIndex]; return result;}
Astor has a theory: I can only guess the author was planning to return some default value in some case..."
I'm sorry, Astor, but you are mistaken. Honestly, if that were the case, I wouldn't consider this much of a WTF at all, but here we have a subtle hint about deeper levels of ignorance, and it's all encoded in that little var.
C# is strongly typed, but declaring the type for every variable is a pain, and in many cases, it's redundant information. So C# lets you declare a variable with var, which does type interpolation. A var variable has a type, just instead of saying what it is, we just ask the compiler to figure it out from context.
But you have to give it that context, which means you have to declare and assign to the variable in a single step.
So, imagine you're a developer who doesn't know C# very well. Maybe you know some JavaScript, and you're just trying to muddle through.
Okay, I need a variable to hold the result. I'll type var result. Hmm. Syntax error. Why?"
The developer skims through the code, looking for similar statements, and sees a var / new construct, and thinks, Ah, that must be what I need to do!" So var result = new ResearchControl() appears, and the syntax error goes away.
Now, that doesn't explain all of this code. There are still more questions, like: why not just return researchControls[index] or realize that, wait, you're just indexing an array, so why not just not write a function at all? Maybe someone had some thoughts about adding exception handling, or returning a default value in cases where there wasn't a valid entry in the array, but none of that ever happened. Instead, we just get this little artifact of someone who didn't know better, and who wasn't given any direction on how to do better.
[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!