Recent Articles

Aug 2023

I Feel Asleep

by in CodeSOD on

When your program needs to pause, there are several options. The first is a pure busy loop- usually a bad idea, but frequently more efficient for very short delays than other options. The "standard" is to sleep your program- just tell the OS scheduler to let other programs run and to wake you up after some interval. In multithreaded programs, you'll frequently sleep one thread while waiting on others.

Which is what Cisco's co-worker sort of did. Sort of.


Serialization and Deserialization

by in CodeSOD on

Over 15 years, an intranet application with a small userbase has gradually become "mission critical". The original developers and all of the maintainers have been folks who didn't have any software development experience, beyond "I took a bootcamp once ten years ago" and "I can do Excel macros". At least they didn't 15 years ago, but over the past 15 years, it's turned into some people's full time job.

Krister E. was hired to try and turn this into a mature software product that didn't require constant babysitting and tending to keep it from crashing, burning, exploding, and leaving a cloud of fallout behind it. There were some challenges to that.


The Debugging Tool

by in Feature Articles on

When Allan C's company, Initrode, got acquired by Initech a few years ago, it sounded like actually good news for the rank and file employees. Initech had a product in the same line of business as Allan's employer, and it was better in most ways, at least according to customer feedback. Allan's team had built some features into their product that Initech wanted, and Initech was also looking to grow rapidly, so there was no fear of layoffs. In fact everybody got a mild raise, and only a few middle managers were asked to leave the company.

That's about where the good news ended.


Negative Creep

by in CodeSOD on

Candice has inherited some legacy C++ code. It's legacy enough, for example, that there are about 15 definitions of a boolean, depending which headers you include. It contains, in Candice's words, "an ambitious attempt to #undef return".

In short, there are plenty of horrors in the code. But this particular short snippet is the one that drew Candice's attention.


The Chemistry Is Gone

by in Error'd on

Sometimes the spark just isn't there.

For instance, Eric R. is just not that into Chemical Engineering. "Looks like I'll still be missing your articles, then, huh?"


Page Up? Page Down. Thumbs Down.

by in CodeSOD on

Putting a full-featured IDE on every user's desktop and providing them basically no guidance on how to use it would, in most circles, be considered a mistake. That mistake is also known as "Microsoft Office", which continues to haunt us.

Now, much of the macro-based application development in Office applications is written by non-programmers. But there's still a disturbing amount of code written by people who should know better, and thus you end up with mission-critical applications written in Microsoft Access.


Functionally Null

by in CodeSOD on

Starting in Java 8, Java introduced support for lambdas. Under the hood, they're a soup of anonymous classes, generics (and the associated type erasure), but they at least look like (and mostly behave like) lambdas. Functional programming came to Java a decade ago.

Ich's predecessor saw this new tool and decided that they needed to use it everywhere.


Simple Form Validation

by in CodeSOD on

"This is so easy, how could someone screw it up?" is a wonderful case of ambiguity in English. Because the question means two things, potentially. The first question is "how (is it possible) that someone could screw it up?" This question is is built upon the assumption that there are limits to how dense people can be, which is a faulty assumption: there are no limits.

The other interpretation is "in what way can someone screw it up?" This is a far more interesting question, as human error is and endless array of fractal snowflakes, no two exactly alike.


More and More Replacements

by in CodeSOD on

You can do a lot in an SQL query. But sometimes, you should probably do less, like this ad-hoc ORDER BY clause from KT.

sql = sql + "Order By Section, " +"replace(replace(replace(replace(" +
    "replace(replace(replace(replace(replace(replace(replace(replace" +
"(replace('.' +Num + '.','.2.','.02.'),'.1.','.01.'),'.3.','.03.')" +
        ",'.4.','.04.'),'.6.','.06.'),'.5.','.05.'),'.7.','.07.')" + 
        ",'.8.','.08.'),'.9.','.09.'),'.5.','.05.'),'.1.','.01.')" +
        ",'.2','.02'),'.3','.03')";

Short Films

by in Error'd on

Frequent flier Carlos quickly quipped "I’m waiting for my plane to take off from Washington-Dulles to Chicago-Midway. Just enough time to watch Innerspace."


John Told Us

by in CodeSOD on

Comments are an important part of making code comprehensible to other people, especially when they explain the why- linking lines of code to requirements, specification documents, etc. Karl used to work for a large company that maybe didn't see comments that way.

So, for example, when you see a line of code like this:


Random Comparison

by in CodeSOD on

Justin's co-worker needed to validate a UUID/GUID in C#. So they wrote this:

if (objectId == null || objectId.ToString() == (new Guid()).ToString())
{
        result = new Error(Error.ERR_REQUEST_INVALID);
}

Randomly Switching Images

by in CodeSOD on

Ronald writes:

I've been asked to take over a website. The first thing I found was this little gem. I'm afraid to go on…


Array Length Validation

by in CodeSOD on

Mike sends us some VB.Net code today.

For fileDataCount = 0 To 4 Step 1
 Try
  Dim dataValidate As String = fileData(fileDataCount).ToString
 Catch ex As Exception
  error = 1
 End Try
Next

All Wet

by in Error'd on

Today JP wrote in to proudly unsmirch the Finnish reputation. "Some time ago, you blamed the Finns for strange patterns on Valts's weather map. I am delighted to report that the *real* culprit is revealed when carefully examining the Finnish Meteorological Institute's weather map of the whole of Europe." I stand corrected, JP.


A Piece of Switch

by in CodeSOD on

Functional programming is fine. It's a different way of thinking about programs, but it makes some problems very easy to describe. It's a tool that belongs in the toolbox, and you should use the right tool for the job.

LH's co-worker doesn't quite take that approach. Their solution to pretty much every problem is to use lambdas, and the functional switch expression in C#. But, when combined with their coding style, it creates some… interesting code.


A Case of Conversion

by in CodeSOD on

Mattijs's co-worker was responsible for an HTML-to-PDF converter that was used internally. While TRWTF is always going to be PDFs, there were some odd choices used in the converter, starting with the function named ConvertTagsToLowerCase.

private static string ConvertTagsToLowerCase(string RichText)
{
        //remove any double tags which are not in SupportedDoubleTags />         
        char[] array = new char[RichText.Length];
        int arrayIndex = 0;
        bool inside = false;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < RichText.Length; i++)
        {
                char let = RichText[i];
                if (let == '<')
                {
                        inside = true;
                        //clear stringbuilder
                        sb.Remove(0, sb.ToString().Length);
                        continue;
                }
                if (let == '>')
                {
                        inside = false;
                       
                        array[arrayIndex] = '<';
                        arrayIndex++;
                        string HTMLInside = sb.ToString().ToLower();
                        for (int j = 0; j < HTMLInside.Length; j++)
                        {
                                array[arrayIndex] = HTMLInside[j];
                                arrayIndex++;
                        }
                        array[arrayIndex] = '>';
                        arrayIndex++;
                        continue;
                }
                if (!inside)
                {
                        array[arrayIndex] = let;
                        arrayIndex++;
                }
                else
                {
                        //append to the string inside
                        sb.Append(let);
                }
        }
        return new string(array, 0, arrayIndex);
}

Universal Catch

by in CodeSOD on

A common pattern is "global error handlers"- functions you call in your catch block that do some task, usually logging, when an exception occurs. Given that exception handling frequently involves a fair bit of repeated code, centralizing that isn't a terrible idea. So when Magnus found code like this in the codebase, he didn't think much of it:

public List<ErrandComboClass> GetErrandCombo()
{
    List<ErrandComboClass> list = null;
    try
    {
        using (MyEntities my = new MyEntities())
        {
            list = my.Errand.Select(x => new ErrandComboClass { ID = (int)x.Id, Name = x.Dnr }).OrderBy(x => x.Name).ToList();
        }
    }
    catch (Exception ex)
    {
        ExceptionHelper.CatchError(ex);
    }

    return list;
}

Load, Load, Load your Deps

by in CodeSOD on

It's not uncommon for web applications to fetch key dependencies from remote, public CDNs. Why host Angular or jQuery yourself, when Google will do it for you? That, at least, was part of the logic underpinning this old code Dan found.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/jquery.js"></script>

Oldies are Goodies

by in Error'd on

Sharp-eyed Jeremy P. goes a little meta, and we like little em meta. "Seen on a well known web site that publishes technology snafus.
I just think that if you are going to redact a company's name from a screen shot, you should probably also react the URL of the page from which the screen shot was made. Whether you publish this or not, I'd be grateful if you would tell me how many other people have also submitted this one." Only you, Jeremy. I'm not sure what that says about the readership of that website you're talking about. It must not be very popular.


Error While you Wait

by in CodeSOD on

Structured exception handling is a powerful way to describe how your program reacts to error conditions. But it's not available in a language like C, and thus C programmers have come up with a variety of ways to propogate errors. Frequently, functions simply return error codes. Some error handling practices use the dreaded goto to jump to the error handler.

Or, they do what "Maple Syrup"'s predecessor did for all of their error handling code:


All Thumbs

by in CodeSOD on

Nick L supports a hardware system that should autodetect a USB drive when inserted, and then load a config file off of it. This fairly simple task is made more complicated by the freelancer they hired to solve the problem, who has some… interesting approaches to writing Python.

thumb_name = []
while thumb_name == []:
    sleep(1)
    thumb_name = os.listdir("/media/update")
    ser.write(bytes("usb drv not detected\r",'UTF-8'))
    print ("test")
    print (thumb_name)
    print ("test")

thumb_name_pure = thumb_name[0]

Taking up Spaces

by in CodeSOD on

Anderson sends us a bit of C# code that does the simple job of removing multiple spaces, i.e. it converts "A    B" to "A B". And, much to my surprise, I learned something about C# from reading this code.

private string RemoveDoubleSpaces(string strName)
{
    string newStrname = null;

    for (int i = 0; i < strName.Length; i++)
    {
        if (i > 0)
        {
            if ((strName[i] == Char.Parse(" ")) && (strName[i] == strName[i - 1]))
            {
                continue;
            }
            else
            {
                newStrname += strName[i].ToString();
            }
        }
        else
        {
            newStrname += strName[i].ToString();
        }
    }

    return newStrname;
}