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.

May 2023

Exceptional Descriptions

by in CodeSOD on

"The Colonial" was trawling through some code they inherited, and found this approach to doing exceptions in C#:

public enum ReturnCode : int
{
      Success                                         = 0,

        Enum1                     = 100,
  Enum2          = 110,

   // *snip* - LOTS of enums
     // .
    // .
   
    UnknownError               = 998,
      Exception                  = 999
};

Trimming Up Your Language

by in CodeSOD on

As a native English speaker, I've inherited a very chaotic perspective on language: "correct" language is defined by usage, loan words are less "loaned" and more like the mandolin someone lent me 20 years ago- mine now. New words can be ginned up on the fly, and parts of speech are just a suggestion.

Many other languages don't take this approach. French, for example, is defined by the Académie Française. There is a standard, and officially correct way to use French. In programming terms, we could say that French is C, while English is Perl.


A Big Ol' Log

by in CodeSOD on

We've already picked on bad logging code this week, but we haven't picked on PHP in awhile, so let's look at some bad PHP logging code, from Kris.

        $path = self::getPath();

        if (file_exists($path)) {
            $content = file_get_contents($path);
        } else {
            $content = "";
        }
        $content .= "\n" . date('Y-m-d H:i') . " | " . $message;
        file_put_contents($path, $content);

Truly Strung Out

by in CodeSOD on

Strings in C remain hard. They're complicated- they're complicated because of null termination, they're complicated because of memory management, they're complicated because of the behaviors of const. There's a lot going on in C strings.

But Alice had a simple case: convert a true or false value into the string "true" or "false". Let's see how her co-worker solved this:


Reopening the Log

by in CodeSOD on

The list of things never to write yourself contains some obvious stars: don't write your own date handling, your own encryption, your own authentication/authorization. It's not that no one should write these things, it's that these domains all are very complicated, require a great deal of specialized knowledge, and while easy to get almost correct, they're nearly impossible to get actually correct. If you embark on these tasks, it's because you want to create a product that solves these problems, hopefully not because you've got a terminal case of NIH syndrome.

While it's not as big a star on the list, another domain you probably shouldn't try and solve yourself is logging. Today's anonymous submission isn't the worst home-grown logging I can imagine, but it's got enough bad choices in it to merit some analysis.


An Operating Query

by in CodeSOD on

Sami inherited some C# LINQ code. The actual behavior and purpose of this code is fairly simple. The way the code was written, however, well…

foreach (var operatingMode in ahu.CalculationData.OperatingModes) { operatingModesModel.OperatingModeNames.Add
(operatingModeNumber, operatingMode.OperatingModeName); var 
innerOperatingModeNumber = operatingModeNumber; foreach (var 
property in from partData in operatingMode.PartDatas.Where(p 
=> p.PartGuid == partGuid) let finalOperatingModeNumber = 
innerOperatingModeNumber from property in (from resultProperty 
in this.GetProperties(partData).Where(p => 
FilterAcceptNonSoundAndNonImageProperties(p, updateResult.For
(partData)) && (propertyFilterFunction?.Invoke(partData, p) ?? 
true)).ToList() let measurementUnit = resultProperty.Type.
GetPresentationMeasurementUnit(measurementUnits) let 
measurementUnitTranslationId = measurementUnit?.TextId select 
new OperatingModesModel.OperatingModePropertyModel
(finalOperatingModeNumber, this.TranslationService.
GetTranslator(this.Language.Code).Translate(resultProperty.
Type.NameId), this.PrintoutUtil.GetValueString(resultProperty, 
measurementUnit, this.Language), string.IsNullOrEmpty
(measurementUnitTranslationId) ? "-" : this.TranslationService.
GetTranslator(this.Language.Code).Translate
(measurementUnitTranslationId), resultProperty.Key)) select 
property) { operatingModesModel.OperatingModeProperties.Add
(property); } operatingModeNumber++; }

Parents In Control

by in CodeSOD on

I've said many unkind things about ASP.Net WebForms in the past. While it leaves a lot to be desired as a web development environment, its event driven approach does map to a lot of folks understanding of software. Click a button, execute code in response. Change a radio button, execute code in response. A simple, easy to understand architecture.

Well, sometimes simple and easy to understand.


intToString

by in CodeSOD on

Krzysztof found themselves staring at a C++ function called intToString. And staring. And then realized that the function makes more sense if you don't look at the name. Let's take a peek:

String intToString(u8* p_param, int p_length) {
	int i;
	int j=0;
	for(i=0; i < p_length; i++)
	{
		j = p_param[i];

		if(j==97 || j==98 || j==99 || j==100 || j==101 || j==102 || j==103 || j==104 ||
			j==105 || j==106 || j==107 || j==108 || j==109 || j==110 || j==111 || j==112 ||
			j==113 || j==114 || j==115 || j==116 || j==117 || j==118 || j==119 || j==120 ||
			j==121 || j==122)
		{
		p_param[i] = j-32;
		}

		if(!isprint((char)p_param[i]))
		p_param[i] = 0;
	}

	string s((char*) p_param);
	return s;
}

The Oracle of Time

by in CodeSOD on

Normally, I wouldn't have much to say about a simple "it's a mere arithmetic error" type of code sample. But this submission from Taylor adds an important factor: it's a basic arithmetic mistake in date handling code, in a legacy product that's been in use for decades. Oh, and it's written in Delphi.

  ElapsedSeconds := Round( (Now - StartTime) * 24.0 * 60.0 * 60.0);

  Days := ElapsedSeconds div 86400;
  Hours := ElapsedSeconds mod 86400 div 3660;
  Minutes := ElapsedSeconds mod 86400 mod 3660 div 60;
  Seconds := ElapsedSeconds mod 86400 mod 3660 mod 60;

Counting Digits

by in CodeSOD on

Denise was supervising a developer who encountered a difficult problem: string handling in C. It's not particularly fun to work with strings in C, but it's certainly feasible.

One of the key issues for strings is that you need to know how large the string is going to be so you can allocate a buffer for it. And while there's a strlen, there is no intlen, so when you want to turn a number into a string, you're faced with a branching path.


Going Tubing

by in CodeSOD on

Emma X maintains some software for a company that does mechanical engineering. In this specific case, her software needs to match a part on their equipment to a tube which can hold the part. They're operating on the order of millimeters, so the smallest tube is about 8mm, and the largest is 155mm.

Now, obviously, not every possible millimeter size is possible- from 8mm to 58mm, the possible diameters all proceed at a step of 2mm. Between 60mm and 95mm, the step is 5mm, and between 100 and 150, the step is 10mm. As I describe this problem, you're probably imagining a lookup table of some kind, or maybe just a list of possible diameters generated by for loops or some similar construct. If that were how this worked, the code wouldn't be there.


Exceptional Assignment

by in CodeSOD on

Ellen sends us a very simple WTF today, that she found in production code.

bool condition;

try
{
    condition = true;
}
catch
{
    condition = false;
}

Switching File Types

by in CodeSOD on

Jeremy found this VB.Net code. It has a simple job: return a file back to the client, but with a twist: they don't know what the correct file extension is. So this was their solution for that problem:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If Application("PointsWhere") = "DEV" Then
            Dim strFile As String
            strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".pdf"
            If System.IO.File.Exists(strFile) Then
                Response.ContentType = "Application/pdf"
            Else
                strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".jpeg"
                If System.IO.File.Exists(strFile) Then
                    Response.ContentType = "image/jpeg"
                Else
                    strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".jpg"
                    If System.IO.File.Exists(strFile) Then
                        Response.ContentType = "image/jpeg"
                    Else
                        strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".gif"
                        If System.IO.File.Exists(strFile) Then
                            Response.ContentType = "image/gif"
                        Else
                            strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".bmp"
                            If System.IO.File.Exists(strFile) Then
                                Response.ContentType = "image/bmp"
                            Else
                                strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".png"
                                If System.IO.File.Exists(strFile) Then
                                    Response.ContentType = "image/png"
                                Else
                                    strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".tiff"
                                    If System.IO.File.Exists(strFile) Then
                                        Response.ContentType = "image/tiff"
                                    Else
                                        strFile = Application("UploadPODs").ToString.Trim & Session("PODClaim") & ".tif"
                                        If System.IO.File.Exists(strFile) Then
                                            Response.ContentType = "image/tiff"
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
            Response.WriteFile(strFile)
            Response.End()
        Else
            'This is for Production
            Dim strFile As String
            strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".pdf"
            If System.IO.File.Exists(strFile) Then
                Response.ContentType = "Application/pdf"
            Else
                strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".jpeg"
                If System.IO.File.Exists(strFile) Then
                    Response.ContentType = "image/jpeg"
                Else
                    strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".jpg"
                    If System.IO.File.Exists(strFile) Then
                        Response.ContentType = "image/jpeg"
                    Else
                        strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".gif"
                        If System.IO.File.Exists(strFile) Then
                            Response.ContentType = "image/gif"
                        Else
                            strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".bmp"
                            If System.IO.File.Exists(strFile) Then
                                Response.ContentType = "image/bmp"
                            Else
                                strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".png"
                                If System.IO.File.Exists(strFile) Then
                                    Response.ContentType = "image/png"
                                Else
                                    strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".tiff"
                                    If System.IO.File.Exists(strFile) Then
                                        Response.ContentType = "image/tiff"
                                    Else
                                        strFile = Server.MapPath(Application("UploadPODs")) & Session("PODClaim") & ".tif"
                                        If System.IO.File.Exists(strFile) Then
                                            Response.ContentType = "image/tiff"
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
            Response.WriteFile(strFile)
            Response.End()

        End If


    End Sub

I (fort)RAN So Far Away

by in CodeSOD on

Many years ago, Matt left a position where he developed in FORTRAN, and went off to do other things. The company hired a replacement, and since no one else really understood FORTRAN, they assumed things were fine. Over the course of a decade, their development costs got more expensive, their software got buggier, and deadlines started flying by without a single new feature being released. It took a long time, but they eventually fired Matt's replacement. Since Matt was looking for a new position around that time, he ended up back in the FORTRAN shop: just when he thought he was out, they pulled him back in.

Matt started going through the code that'd been implemented, and… well, here's an example function signature:


Python's Tern

by in CodeSOD on

Python is a language underpinned by a philosophy about how programming should work. It's opinionated. As a result, in the Python world, you'll hear constant debates over what is and is not "Pythonic", and you'll encounter all the weird ways in which the Python philosophy and real-world programming needs conflict: for example, you don't use switch statements in Python, you put callable functions in a dict instead.

I bring that case up, specifically, because Python's philosophy is that there should be one correct way to do everything: since if statements handle branches, switch statements are unnecessary. Ternaries are also unnecessary by that rule- but they exist and Python has its own twist on them.


Extra Documentation

by in CodeSOD on

Tony works in a shop that makes extensive use of XMLDocs comments. Now, it's no surprise that many of the comments take the form:

/// <param name="MyParam">My param</param>
public void Foo(int MyParam)

In the Area (code)

by in CodeSOD on

Jeremy was sent hunting a bug in some older JavaScript code. The key problem was that many phone numbers were getting a US country code prepended to them, even when they already had a different country code and were in a different country than the US.

for(i in item.victims) {
        c = item.victims[i].country_code;
        n = item.victims[i].phone_number;
                               
        if(n) {
                number = c ? c + '' + n : n
                if(number in Account.contacts) {
                        number = Account.contacts[number];
                } else {
                        if(n.length == 10 || (n[0] == 1 && n.length > 10)) {
                                s = n[0] == 1?1:0;
                                number = '1 (' + n.substring(s, s+3) + ') ' + n.substring(s+3, s+6) + '-' + n.substring(s+6, s+10);
                        } else {
                                number = '+' + c + ' ' + n;
                        }
                }
                victims.push(number);
        }
}