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.

Feb 2026

The Counting Machine

by in CodeSOD on

Industrial machines are generally accompanied by "Human Machine Interfaces", HMIs. This is industrial slang for a little computerized box you use to control the industrial machine. All the key logic and core functionality and especially the safety functionality is handled at a deeper computer layer in the system. The HMI is just buttons users can push to interact with the machine.

Purchasers of those pieces of industrial equipment often want to customize that user interface. They want to guide users away from functions they don't need, or make their specific workflow clear, or even just brand the UI. This means that the vendor needs to publish an API for their HMI.


Safegaurd Your Comments

by in CodeSOD on

I've had the misfortune of working in places which did source-control via comments. Like one place which required that, with each section of code changed, you needed to add a comment with your name, the ticket number, and the reason the change was made. You know, the kind of thing you can just get from your source control service.

In their defense, that policy was invented for mainframe developers and then extended to everyone else, and their source control system was in Visual Source Safe. VSS was a) terrible, and b) a perennial destroyer of history, so maybe they weren't entirely wrong and VSS was the real WTF. I still hated it.


Terned Backwards

by in CodeSOD on

Antonio has an acquaintance has been seeking career advancement by proactively hunting down and fixing bugs. For example, in one project they were working on, there was a bug where it would incorrectly use MiB for storage sizes instead of MB, and vice-versa.

We can set aside conspiracy theories about HDD and RAM manufacturers lying to us about sizes by using MiB in marketing. It isn't relevant, and besides, its not like anyone can afford RAM anymore, with crazy datacenter buildouts. Regardless, which size to use, the base 1024 or base 1000, was configurable by the user, so obviously there was a bug handling that flag. Said acquaintance dug through, and found this:


Contains Some Bad Choices

by in CodeSOD on

While I'm not hugely fond of ORMs (I'd argue that relations and objects don't map neatly to each other, and any ORM is going to be a very leaky abstraction for all but trivial cases), that's not because I love writing SQL. I'm a big fan of query-builder tools; describe your query programatically, and have an API that generates the required SQL as a result. This cuts down on developer error, and also hopefully handles all the weird little dialects that every database has.

For example, did you know Postgres has an @> operator? It's a contains operation, which returns true if an array, range, or JSON dictionary contains your search term. Basically, an advanced "in" operation.


Waiting for October

by in CodeSOD on

Arguably, the worst moment for date times was the shift from Julian to Gregorian calendars. The upgrade took a long time, too, as some countries were using the Julian calendar over 300 years from the official changeover, famously featured in the likely aprochryphal story about Russia arriving late for the Olympics.

At least that change didn't involve adding any extra months, unlike some of the Julian reforms, which involved adding multiple "intercalary months" to get the year back in sync after missing a pile of leap years.


C+=0.25

by in CodeSOD on

A good C programmer can write C in any language, especially C++. A bad C programmer can do the same, and a bad C programmer will do all sorts of terrifying things in the process.

Gaetan works with a terrible C programmer.


Consistently Transactional

by in CodeSOD on

It's always good to think through how any given database operation behaves inside of a transaction. For example, Faroguy inherited a Ruby codebase which was mostly db.execute("SOME SQL") without any transactions at all. This caused all sorts of problems with half-finished operations polluting the database.

Imagine Faroguy's excitement upon discovering a function called db_trans getting called in a few places. Well, one place, but that's better than none at all. This clearly must mean that at least one operation was running inside of a transaction, right?


Cover Up

by in CodeSOD on

Goodhart's Law states that when a measure becomes a target, it ceases to be a good measure. Or, more to the point: you get what you measure.

If, for example, you measure code coverage, you are going to get code coverage. It doesn't mean the tests will be any good, it just means that you'll write tests that exercise different blocks of code.


Invalid Passport

by in CodeSOD on

Gretchen wanted to, in development, disable password authentication. Just for a minute, while she was testing things. That's when she found this approach to handling authentication.

passport.authenticate('local', { session: true }, async (err, user) => {
  if (err) {
    res.send({ success: false, message: 'Error authenticating user.' })
  } else if (!user) {
    User.query()
      .where({ username: req.body.username })
      .first()
      .then(targetUser => {
        if (targetUser) {
          const hash = User.hashPassword(
            targetUser.password_salt,
            req.body.password
          )
          if (hash === targetUser.password_hash) {
            res.send({
              success: false,
              message: 'Incorrect username or password.',
            })
          } else {
            res.send({
              success: false,
              message: 'Incorrect username or password.',
            })
          }
        } else {
          res.send({
            success: false,
            message: 'Incorrect username or password.',
          })
        }
      })
      .catch(err => {
        res.send({ success: false, message: 'Internal server error' })
      })
  } else if (user.firstLogin) {
//......
  }
})(req, res, next);

Brillant Python Programmers

by in CodeSOD on

Sandra from InitAg (previously) tries to keep the team's code quality up. The team she's on uses CI, code reviews, linting and type checking, and most important: hiring qualified people. Overall, the team's been successful recently. Recently.

The company got its start doing data-science, which meant much of the initial code was written by brilliant PhDs who didn't know the first thing about writing software. Most of that code has been retired, but it is impossible to dispatch all of it.


This Router Says **** You

by in CodeSOD on

Denilson uses a password manager, like one should. Except there was a router which simply would not let the password manager fill the password field. Sure, Denilson could just copy and paste, but the question of why remained.

And that meant checking the HTML and JavaScript code the router served up. Just pulling up the dev tools brought up all sorts of "fun" discoveries. For example, the application was built in Vue, a front-end framework. But in addition to using Vue, it also used jQuery for some DOM manipulations. But it didn't just use jQuery. It loaded jquery-3.5.1.slim.min.js directly from its static files. It also loaded vendor.js which also contained the same version of jQuery. At least it was the same version.


A Percise Parser

by in CodeSOD on

Thomas worked for a company based in Germany which was looking to expand internationally. Once they started servicing other locales, things started to break. It didn't take long to track the problem down to a very "percise" numeric parser.

handleInput( value ){
   let value_ = value;
   if( value.substring( 0, 1 ) === '+' ){
      value_ = value.substring( 1 );
   }

   value_ = value_.split( '.' ).join( '' );

   if( this.usePercisionIfPercentage && value_.indexOf( ',' ) >= 0 ) {
      const parsedPreValue = value_.split( ',' )[ 0 ];
      const parsedCommaValue = parseInt( value_.split( ',' )[ 1 ], 10 ) < 10 ?
         parseInt( value_.split( ',' )[ 1 ], 10 ) * 10 : value_.split( ',' )[ 1 ].substring( 0, 2 );

      if( parsedCommaValue === 0 ) {
         value_ = parseInt( parsedPreValue, 10 );
      }
      else {
         const parsedValue = parseInt( parsedPreValue + parsedCommaValue, 10 );
         value_ = parseInt( parsedValue, 10 ) / 100;
      }
   }
   
   // do stuff with value_
}

Wages of Inheritance

by in CodeSOD on

Tim H writes:

Some say that OOP was the greatest mistake of all. I say they weren't trying hard enough.