Recent CodeSOD

Code Snippet Of the Day (CodeSOD) features interesting and usually incorrect code snippets taken from actual production code in a commercial and/or open source software projects.

Mar 2023

Exceptional Messages

by in CodeSOD on

Structured exception handling is an excellent way to handle errors, but wouldn't it be nice if you could execute a different branch of code depending on what specific error just happened? It's a pity that there's just no possible way to filter exceptions using the good old fashioned try and catch. Fortunately, Mateusz has a co-worker who invented that wheel for us.

if (something_bad_happens)
        throw new Exception("File is not correct; 88888");

if (something_else_happens)
        throw new Exception("Tag len exceeded; 1337"); 
...

catch (Exception ex)
{
    if (ex.Message.Contains("88888"))
    {
                ...
    }
    else if (ex.Message.Contains("1337"))
    {
            ...
    }      
}

Closely Related

by in CodeSOD on

Relational databases were at one time an absolute standard that nearly any developer could be expected to be familiar with. These days, it's still valuable knowledge, but it's less surprising when someone doesn't know more than the basics- there are so many other ways one might persist data, each with their own tradeoffs. But if someone is developer for a contracting firm specializing in data driven applications, you would expect them to have a little more grounding in RDBMSes than the average developer. Well, you would expect that if you thought the contracting firm was actually selling a valuable service, instead of trying to bilk their customers and their contractors and hope nobody notices.

The important things about RDBMSes is that each table represents a relation- a set of fields that are all conceptually related, like "Employee" (with an employee ID, a name, a hire date, etc.) or "SalesListing" (with a product description, a price, etc.), and then those tables can have relationships to other tables- foreign keys that guarantee that if "SalesListing" has a "SalesRep" field on it, that "SalesRep" has a matching entry in the "Employee" table.


An Accountable Service

by in CodeSOD on

While the world has switched to RESTful APIs, the magical power of SOAP-based web-services was that they made code generation easy. Well, easy-ish. Well, easy when it worked right, and then hard the rest of the time. But if it worked, if the WSDL was up to date and sane, you'd get a nice client-side API to invoke methods on the remote server.

Andrew inherited one such client-side C# API. It looked something like this:


Time Changes

by in CodeSOD on

Dates and times are way more complicated than we usually think they are, especially when we're talking about historical dates and times. The solution, of course, is to always use someone else's work, whether it's a library or your language's built-ins, never implement date handling yourself.

For a long time, though, Java's date handling left something to be desired. Which is why Sven found this history lesson in his company's code base:


Tied to the Train Tracks

by in CodeSOD on

Ah, the joys of stringly typed code. Everything can be turned into a string, so why not treat everything as a string? It certainly worked for Sebastian's co-worker, who also took it to another level:

If GetTrainAtStation(aTrainNo.ToString) Is Nothing Then
    iTheTrainAtStation.Add(String.Format("{0}", aTrainNo.ToString), aTrainAtStationItem)
End If

All in the Timing

by in CodeSOD on

We like using constants instead of magic numbers. Today, we see an unusual misuse of them. It's unusual because, while it's a set of bad choices, it's not quite a `#define ONE 1` level of silliness.

First, a little background. Benjamin inherited a building automation system. This building automation system was implemented in Microsoft's Visual C++, version 6.0, way back in the 90s. As of the late 2010s, not only was it still in use, it was still pinned to the same compiler version. So not exactly the most modern of applications, but it accomplished the business goals, albeit with a lot of bugs, errors, and mysterious glitches.


Magical Destruction

by in CodeSOD on

Pretty much all object oriented languages have some concept of "destruction": objects need to release any resources they acquired at construction. In a lot of cases, we don't need to customize this terribly much, but when we do, it's vitally important to do it correctly.

Nancy's co-worker perhaps didn't understand the "correctly" part. So this was the standard pattern of C++ destructor that they wrote:


The Properties of Contract Development

by in CodeSOD on

James's management had more work than they had staffing for, so they did what any company would do in that situation: expand their staff. No, of course not, I'm kidding. They bundled up a pile of work and shipped it off to the contractor who gave them the lowest bid, provided absolutely no oversight or code-quality standards in the contract, and hoped for the best.

What they got back was a gigantic pile of code that compiled. That is the only positive thing one can say about the code, because it certainly didn't work. Within a few weeks of starting reviewing the gigantic pile of garbage the contractors turned in, the dev team reached the decision that it would be quicker to rewrite from scratch than it was to try and pick apart the trashpile and reshaped the refuse into something approaching their actual requirements.


Going to Great Len(gths)

by in CodeSOD on

Mira was trawling through some old Python code. This particular block of code needed to load some data from JSON. The data was an array, and the code needed to know how long the array was.

Python has a handy len function that does this on anything enumerable. If our developer had used len, we'd be looking at different code today.


Terning On a Control

by in CodeSOD on

One of Tim's co-workers needed to handle a simple condition: if a control in their web app was enabled, show it, otherwise hide it.

Now, if you or I were writing that, we might write some awfully verbose code, like:


A False Comparison

by in CodeSOD on

Iterating across a list is a very simple task. It's a CS-101 type thing, and if anything, it's the one thing I'd expect any developer to be able to do without confusing me too much.

Brendan has a co-worker that wants to change my mind about this.


Evaluating Selections

by in CodeSOD on

If you're writing an application with a drop-down list, it's typical and reasonable to auto-select a certain option in the list. But John found an approach to doing this that's anything but typical.

function selectsearch(myform, myselect, myinput) {
    var i = 0;
    var fvalue = 1;
    do {
        arrayresult = eval(myform+"."+myselect+".options["+i+"].value");
        if (arrayresult == myinput) {
            eval(myform+"."+myselect+".options["+i+"].selected = true");
            var fvalue=5;
        }
        i++; 
    } while(fvalue<3);
}

Trying Parses

by in CodeSOD on

Another day, another terrible way to validate integers. Today's submission comes from Sluiper.

This approach, at least, contains a mild bit of cleverness. It's not the good kind of cleverness that makes a complicated problem more clear and easier to understand, but the bad kind that exploits assumptions about low-level technical details.


An Array of Colors

by in CodeSOD on

Sandra, still at InitAg, has to work with Brad. Some time ago, Brad was assigned a slew of front-end development tasks, since he's a web developer. But Brad isn't a front-end developer, and doesn't really have a good grasp of front-end development. Management isn't clear on the difference: "Aren't you a web developer? I don't care which end you use, just develop." Brad is also game to tackle whatever task is assigned to him, regardless of whether he has any sense of how to solve the problem.

When Brad needed to display data on a map, the requirements wanted the map layers to be distinguished by color. So Brad did the usual thing one might do in this situation: he created a gigantic array of all possible colors that might be used on the map. Actually, he created two: colors and colorsBlackWhite.


Peer Feedback

by in CodeSOD on

Pieter-Jan needed to add some features to a PHP-based site for managing student assessments. Students would complete projects, submit them, and then receive feedback from their peers. The number of peers providing feedback is variable, so the application has to manage that. Which, you might be thinking, "that sounds like not a big deal to manage," but for Pieter-Jan's predecessor, it seems like it may have been.

    if($i > '0') {
        $team=array($studentName1,$content1,$motivation1,$isTeamMate1);
    }
    if($i > '1') {
        $team=array($studentName1,$content1,$motivation1,$isTeamMate1,$studentName2,$content2,$motivation2,$isTeamMate2);
    }   
    if($i > '2') {
        $team=array($studentName1,$content1,$motivation1,$isTeamMate1,$studentName2,$content2,$motivation2,$isTeamMate2,$studentName3,$content3,$motivation3,$isTeamMate3);
    }

Evaluating Regexes

by in CodeSOD on

Stack V supports a web application that accepts regexes from users. For legacy reasons, the users must supply the surrounding / characters, as well. There was some validation to ensure that the inputs were correct, but QA discovered that invalid regular expressions were getting through.

They filed a bug, it got triaged, and then shipped off to a contractor to patch. This was the contractor's solution: