Recent Articles

Jul 2024

Yes, No, NO NO NO NO

by in CodeSOD on

Mike was doing work for a mobile services provider. He found this in their code:

private static YesNoType toYesNo(String isYes)
{
		if (isYes != null)
		{
				if (isYes.equalsIgnoreCase("Y"))
				{
						return YesNoType.fromString("Yes");
				}
				else
				{
						return YesNoType.fromString("No");
				}
		}
		else
		{
				return YesNoType.fromString("No");
		}
}

/**
 * @param isYes
 * @return
 */
private static YesNoType toYesNo(boolean isYes)
{
		if (isYes)
		{
				return YesNoType.fromString("Yes");
		}
		else
		{
				return YesNoType.fromString("No");
		}
}

/**
 * @param isYes
 * @return
 */
private static String fromYesNo(YesNoType isYes)
{
		if (isYes != null)
		{
				String resultStr = isYes.toString();
				if (resultStr.equalsIgnoreCase("Yes"))
				{
						return ("Yes");
				}
				else
				{
						return ("No");
				}
		}
		else
		{
				return ("No");
		}
}

/**
 * @param isYes
 * @return
 */
private static boolean isYesNo(YesNoType isYes)
{
	boolean isBroadbandUser =  false;
	if (isYes != null && isYes.toString().equalsIgnoreCase("Yes"))
	{
		isBroadbandUser = true;
	}
	return isBroadbandUser;
}

Mailing it In

by in CodeSOD on

Dan B is working on software which interacts with a bank. We'll get the REAL WTF out of the way right at the top: "The bank has requested that we send them an email containing the total of all the transactions…"

Yes, core financial business functions being handled over email. I imagine some readers are probably thinking about drinking something stronger than coffee at the thought of it. A lot of readers, on the other hand, are already onto something stronger than coffee and going, "Oh, yeah, seen that before. Hell, I'm pretty sure that EDI explicitly supports email as a delivery mechanism."


An Exceptional Junior

by in CodeSOD on

When "dragoncoder047" was but a junior developer, without very much experience at all, they were tasked with building error handling in a Python Flask web application.

Now, they were a junior, and tossed into the problem without much preparation, or much supervision, and just told to "make it work". So they did. With this disaster:


Too Spicy For My Hat

by in Error'd on

My plate has been full this week, but not as full as Walter's!

"Maybe hold the cheese?" suggests Walter T. regarding a pepper and steak grinder. "Seen at Reading (MA) House of Pizza on Jul 24 2024." If you decide to search around to try to understand the different names for this kind of sandwich, you will undoubtedly discover someone trying to claim that really, the hoagie is a different sandwich from a submarine, which is different from a grinder and so on. They are wrong, and this is how we know: if they truly were different kinds of sandwiches, then somewhere on this planet would be a shop selling examples of each of the different variants for your dining pleasure. There is not*. Q.E.D any consistent regional variation in bread choice, or dressing, or fillings, is simply that: a regional variation of the same thing, not an entirely different category.
*Until someone can show me the existence of such a sandwich shop, I assert that it does not exist, thus my proof holds.


Reflections on Privacy

by in CodeSOD on

Jaco's team had a problems with making an embedded web server shut down properly. Something about the shutdown process was deadlocking, so one of their "ninja Yoda coders" rockstarred their way to a solution.

private void stopServer() {
	try {
		if (webServer != null) {
			logger.debug("Shutdown webserver");
			// This goes into a dead lock, therefore I've replaced it with
			// some voodoo stuff.
			logger.debug("Get listener field from web server.");
			Field listenerField = WebServer.class.getDeclaredField("listener");
			listenerField.setAccessible(true);
			Thread listener = (Thread) listenerField.get(webServer);
			listenerField.set(webServer, null);
			logger.debug("Interrupt the listener thread.");
			listener.interrupt();
			webServer = null;
			logger.debug("Shutdown webserver complete");
		} else {
			logger.debug("No webserver to shutdown");
		}
	} catch (Exception e) {
		logger.error(LoggerCodes.RPC_SERVER_SHUTDOWN_FAILURE, e, LoggerUtility.parameters("class",
			e.getClass().getSimpleName(), "message", e.getMessage()));
	}
}

How to Validate an IP Address

by in CodeSOD on

Andy has some concerns about future proofing. In this case, he sends us some C# code that's supposed to validate an IP address.

string[] address = StringTools.splitStr(IP, '.');
if (address.length < 4) {
        throw new Exception("Bad IP format : " + IP);           }

NPath Complexity

by in Feature Articles on

We're not going to look at code today, and instead, we're going to talk about a code metric. Specifically, "NPath complexity".

NPath complexity is a good metric to track, and many static analyzers will do it. Formally written, it's defined: "The NPath complexity of a method is the number of acyclic execution paths through that method." Or, more simply, not counting loop iterations, this is how many branches you have in a single method.


Serial Properties

by in CodeSOD on

Jan wrote some code that set a property, and a few lines later had to write code to read that value- and the compiler complained. Which is what drew his attention to this C# code:

public string ViewNodeFilter
{
        protected get
        {
                if (viewNodeFilter.IsNotValid())
                {
                        return "null";
                }
                return new JavaScriptSerializer().Serialize(viewNodeFilter);
        }
        set { viewNodeFilter = value; }
}

Pennies From Heaven

by in Error'd on

Adrian M. lit up this blooper for us. "Apparently Siemens Mobility wasn't satisfied that a mere 95-year copyright term would be enough for the brochure about their m60-series traffic light controller. I hope I won't have to wait until 2029 for a green light." See for yourself here.


False True is True False

by in CodeSOD on

Languages which do type-coercion are generally setting users up for failure. At some point, you'll make some assumption about your inputs, and then type-coercion kicks in and changes what you expect. We see this all the time in JavaScript, and of course, in PHP. PHP booleans, for example, can surprise you: 0 is false, which is a common enough assumption, but so is "0"- the string zero. As are empty arrays.

But what if you wanted more control over it? Peter sends us this PHP he found:


Sanitary Paths

by in CodeSOD on

When accepting user input for things like, say, accessing the filesystem, you need to do some validation. Bad or inappropriate characters could lead to surprises that no one is going to like.

So when Christian first spotted this C# method called SanitizePath, he didn't think much of it. But then he looked at the implementation…


Prefixual

by in CodeSOD on

Maciek has the distinct pleasure of working on Dynamics Ax, and ERP system. Like every other ERP system, it's endlessly customizable, and scriptable. In this case, scriptable in a custom language called "X++".

While it's probably entirely possible to write good code under these circumstances, it's not an environment conducive to that. And that's how Maciek inherited this method:


Uniquely Enough Identifiers

by in CodeSOD on

Running and hosting a database is expensive. Not only do you need the server for it (even if you rent in the cloud), you also need the expertise to administer it. And that's why Lucas ended up working on an application which used Google Sheets as its database.

Now, this was an application used by a marketing team to create new marketing campaigns, so Google Sheets wasn't the worst choice made in the entire process. With only a handful of users and dozens of records, it was fine. You didn't need to put a huge amount of effort or expertise into it- at least, that's what management thought.


Watching the Days

by in Error'd on

This week, we saw some unexpected results in UK politics. Nothing was more unexpected than the dark-horse results that Richard and a few anonymice remarked on.

"A glorious victory for the Undefined party!" crowed Richard "The UK general election has seen a surge of support for minor parties."


Classic WTF: Cluster#$%&

by in Best of… on
Reliability is its own, very important art. Unless you're, say, Google, you shouldn't write your own reliability systems, but instead buy solutions from a vendor. Just not this vendor. Original. --Remy

Image credit: 'Mark Bowytz' - REMEMBER THE KRAKEN!!!It was a little past 4AM when Massimo's support pager went off, jarring him awake. Without even looking at the pager or logging into his laptop, he flipped on the television to Channel 242: the Video on Demand channel for the Italian TV broadcaster that he worked for.

Nothing.


Classic WTF: Python Charmer

by in Best of… on
When comparing your language to a snake*, be careful to not get bitten. (*Yes, I know, the name of the language is a reference to Monty Python, not snakes). Original. --Remy

"I don't have a whole lot of experience in Python," writes Jakob, "in fact, when I was hired, the only thing I knew about the language was that whitespace was important."

"Fortunately — actually, unfortunately — it doesn't take a whole lot of experience in Python to recognize that my company's codebase is... well... sub-optimal. Submitted for your approval is a method used to generate a password, found in our network security library."


Classic WTF: What's in a Name?

by in Best of… on
We continue our summer break. Sometimes, you need to make a bad choice in your design, and you can often "fix" that, with documentation. "Don't touch the sharp pointy bit." But, not to spoil the ending, sometimes the documentation raises more questions than it answers. Original. --Remy

The year was 1993, and that meant one thing: Old Iron was finally ready for the scrap yard retirement after nearly fifteen years of faithful service to the university. Technically, the MVS-based mainframe had been well past its prime for quite a many years, but since it was used primarily as a data repository for research projects, no one seemed to mind. But what they would mind, however, was any sort of downtime in the transition to the new, UNIX -based research computer, so it was up to Todd M. Lewis to figure out how to ensure things went smoothly.

In order to give researches the opportunity to learn their way around Unix and adjust their processes for the new environment without disrupting ongoing work on Old Iron, Todd set up a migration process that would pull MVS data sets from the backup system (as not to interfere with “live” data sets users may be using) and copy them to an archive on the UNIX server. From there, users could check out copies from this archive and work with them under UNIX to hone their processes. If they screwed up the data, they could just check it out again from the archive.


Classic WTF: XML Anybody?

by in Best of… on
We're taking our summer break, which means we reach back into the archives and find some classics. This one teaches you everything you need to know about generating XML. --Remy

XML is an absolutely wonderful innovation. It allows us to easily describe and share just about any data immaginable. Of course, there's always gotta be someone (as Tim points out) who has to go and ... well ... see for yourself ...


That Movie with Whatsisname

by in Error'd on

This week's special edition is a series of Error'ds specifically dealing with trains, which geeks are for some reason especially taken with. It should go without saying that the reason these are predominantly from Europe is not an indication their infosystems are especially bad, but rather as we all know, US passenger trains are so little used that there is far less opportunity to discover any wtfs.

This entry by Robert G. requires explanation. London North East Rail has a novel (six years old now but still new to me) point-of-use display of seat reservations. In my train experience, a reserved seat ticket only identifies a certain car but not a specific seat, so this is pretty slick. On LNER, if you don't have a seat reservation but you're traveling in the specified class, you can take any seat labelled "Available" but you'll need to vacate it at the "until XXX" station. The two rows in Robert's fuzzy image read "Current" and "Next", which should help to understand what has happened here. The two red lights indicate "Reservations". As Robert puts it, "My train was part cancelled, and a replacement coach was provided to where it was now starting from. Unfortunatly the coach arrived a few minutes after the train departed, so a new train was needed. Fortunatly the TOC's (Train Operating Company) app allows seat reservations to made up to 10 minutes from departure and the next train was in half an hour - given it's a long journey I was going to get a reservation. Apparently several other people had the same idea, resulting in two of us getting a confirmation (both email and in app) for the same seat." Apparently Robert reserved Edinburgh->KingsX and a random competitor reserved Newcastle->KingsX at the same time. It seems that LNER's seat reservation application had a failure of transactional integrity. Hopefully it was eventually consistent.


Classic WTF: For Each Parallel

by in Best of… on
It's a holiday in the US today, where we celebrate with a lot of explosive-induced accidents and emergencies. Instead of holding a cherry bomb until it's too late, let's instead look at some explosively parallel code. Original. --Remy

Parallel programming is hard. For all the advancements and tweaks we've made to our abstractions, for all the extra cores we've shoved into every CPU, deep down, software still carries the bias of the old uni-tasking model.

Aleksei P works on a software package that is heavily parallel. As such, when interviewing, he talks to candidates about their experience with .NET's Task objects and the async/await keywords.


Looks Guid to Me

by in CodeSOD on

Today, we have an interesting one. It's not technically a Code SOD, because it doesn't have any code. It isn't quite a feature, because it doesn't contain a story. It's just some data, from a database table.

But it does tell a story.


Certificate of Security

by in CodeSOD on

Joe wanted to interact with a social media service's API. As one does, he went out and found a library for his language, and started investigating it. Now, the API was, unsurprisingly, an HTTP based API, wrapped in TLS for security. The library had a handy built-in function which validated the security certificates to ensure they were still valid and hadn't been compromised:

Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
    Return True
End Function

Black Letters

by in CodeSOD on

Johannes started debugging an application, and decided he needed to "share his pain".

Here, we're presented with a simple problem: convert a number in the range [0-25] to a letter [A-Z]. Many people would solve this with an array of letters as a lookup table. If they're clever, they'd leverage the character encoding and do some arithmetic.