CodeSOD: An Impossible Problem
One of the lines between code that's "not great, but like, it's fine, I guess" and "wow, WTF" is confidence.
For example, Francis Gauthier inherited a WinForms application. One of the form fields in this application was a text box that held a number, and the developers wanted to always display whatever the user entered without leading zeroes.
Now, WinForms is pretty simplistic as UI controls go, so there isn't really a great "oh yes, do this!" solution to solving that simple problem. A mix of using MVC-style patterns with a formatter between the model and the UI would be "right", but might be more setup than the problem truly calls for.
Which is why, at first blush, without more context, I'd be more apt to put this bad code into the "not great, but whatever" category:
int percent = Int32.Parse(ctrl.Text); ctrl.Text = percent.ToString();
On an update, we grab the context of the text box, parse it as an integer, and then store the result back into the text box. This will effectively strip off the leading zeroes.
It's fine. Until we zoom out a step.
// Matched - Remove leading zerotry { int percent = Int32.Parse(ctrl.Text); ctrl.Text = percent.ToString();}catch { // impossible..}
Here, we can see that they... "wisely" have wrapped the Parse in an exception handler. The developer knew that there was a validator on the control which would prevent non-numeric characters from being entered, and thus they were able with a great degree of confidence to declare that an exception was "impossible".
There's just one problem with that. The validator in question allows numeric characters, not just integer characters. So the validator would allow you to enter 0.99. Which of course, won't parse. So the exception gets triggered, the catch ignores it, the user believes their input- a percentage- has been accepted as valid. The end result is that many users might enter "0.99" to mean "99%", and then see "0" be what actually gets stored as the unexpected floating point gets truncated.
All because an exception was declared "impossible". To misapply a quote: "You keep using that word. I do not think it means what you think it means."
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!