CodeSOD: A Type of HPC
Matteo's company hired a Highly Paid Consultant. The HPC came in, took one look at their C# codebase, and said, "You're doing everything wrong. But don't worry, I can fix it!"
So he "fixed" it.
For example, what if you had a string, and needed to parse it to some concrete type. Why, you just do this:
public static T ToType<T>(this string value, T defaultValue){ if (string.IsNullOrEmpty(value)) { return defaultValue; } T result = defaultValue; try { result = (T) Convert.ChangeType(value, typeof (T)); } catch { } return result;}
This particular code doesn't do very much at all- a basic null check followed by an attempt to convert, a swallowed exception and a default value output. There are built-in methods, like Int32.TryParse, but that wouldn't work well with using generics. I don't love it, but it's not WTF.
public static T? ToNullable<T>(this string value) where T : struct{ if (string.IsNullOrEmpty(value)) { return null; } T? result = null; try { result = (T) Convert.ChangeType(value, typeof (T)); } catch { } return result;}
It's the same method, but this time where the default value is a nulled nullable. The real bonus here is that this time, they qualified the generic to require it to be a struct- which in C# terms actually requires it to be a "value type". Which, as an aside, Convert.ChangeType requires its type parameter to be a value type- which means for consistency, they probably should have put that qualifier on ToType.
Again, this code, alone, isn't really a full on WTF. So we need to put it into context: this is the Highly Paid Consultant's home-grown JSON library, which handles both parsing and generating JSON.
Now, we're getting the sense that someone's been reinventing the wheel, awkwardly. So let's look at one last method- ToJS. What do you think ToJS does? If you said, "clearly, this must be what converts an object to JSON", you'd be wrong.
public static string ToJS(this string text){ return text.Replace(@"\", @"\\") .Replace(@"'", @"\'") .Replace("\"", "\\\"");}
This just escapes your strings for you.
There's one last piece of context: all of the code this developer wrote, every method that could throw an exception had a handy, dandy, exception handler. That handler logged the exception and did nothing else.
Like a damp fart, the HPC hung around the office for awhile, and then slowly dissipated to another contract. The stench, however, is going to take Matteo some scrubbing to remove.
[Advertisement] ProGet's got you covered with security and access controls on your NuGet feeds. Learn more.