Feed the-daily-wtf The Daily WTF

Favorite IconThe Daily WTF

Link http://thedailywtf.com/
Feed http://syndication.thedailywtf.com/TheDailyWtf
Updated 2024-07-01 13:17
CodeSOD: Never Refuse a Fifth
Sometimes, you want your dates to look like this: 3/3/2019. Other times, you want them to look like this: 03/03/2019.There are plenty of wrong ways to do this. There are far fewer right ways to do it, and they mostly boil down to “use your language’s date library.”And then there’s this, which “QuakePhil” found.
An Excelent Start to a Career
Hal was a wiz kid computer programmer at age 15 in 1976. He could make the toggle switches and LEDs on his Altair 8800 dance at will. In college, he was class valedictorian after earning his computer science degree in 1984. Hal was destined for greatness and the real world was about to get rocked.Hal's college friend Victor, who graduated two years prior, was already running his own startup company that made Unix-based financial planning software. Remembering Hal's brilliance, Victor recruited him to join his company the day after graduation. Victor needed the wiz kid-turned-wiz adult to create the equivalent of Lotus 1-2-3 in Unix. It was a tall first project but it paid well, so Hal happily signed up. Besides, everyone knew that spreadsheets were gonna change the world.Hal was so full of ideas, he felt like he could take Lotus 1-2-3 and make it better. He built Unixus 3-2-1 from scratch and vowed to turn it into a fun and useful program. Surely it was bound to make Victor's company millions upon release.Victor didn't seem to notice Hal's efforts, though. He was seldom in the office any more, the parking spot for his Porsche frequently sitting empty. Whenever Victor was actually around, he seemed disheveled and claimed to be preparing for an important sales trip. There were myriad rumors going around that he was actually out partying with the cashflow from their first big sales.One day, Hal came in to work only to find the doors chained shut. A note from Victor was taped to the door. In it, he explained how the company was going bankrupt and he had to sell it for pennies on the dollar to a larger tech firm. All of the company's assets now belonged to the new ownership, and everyone was out of a job. Hal felt crushed that he lost his first job in addition to his source code for Unixus 3-2-1.Many years went by and Hal moved on to more stable employment. He initially held a strong resentment towards Victor but it gradually faded with each passing year. Victor too had found himself some more stability and his hard partying days were over. Victor and Hal eventually reconnected through a mutual friend."Hal! Good to see you, old buddy!" Victor shouted, rising from the restaurant table he reserved for them. Hal shook his hand, less enthusiastically than Victor did. "Hey, I just want to say right away that I'm sorry about the whole company closure way back when. I was young and immature and I felt so bad about costing everyone their jobs," Victor dropped his head, showing that his 80's permed hair was long gone."Hey, don't worry about it. It wasn't a big deal," Hal downplayed, failing to mention how he used to throw darts at a picture of Victor. Hal started to open up more while they reminisced about wild college stories. Victor's memory of things… was a bit different. Specifically, he was always the center of every story. He always was the big winner in every bit of college hijinks, and if Hal remembered anything embarassing about Victor, it was Hal's memory that was faulty- Victor was King of the School.They eventually got around to talking about Unixus 3-2-1. "I know it was my first real project, but I felt like my spreadsheet program was really something. What ever happened to all the source code from that place?"Victor laughed, "Oh Hal, you won't believe this! Most of our products were scrapped or hacked to bits and repurposed. But they realized Unixus 3-2-1 had potential. They added a few finishing touches then packaged it up and sold it off. Boy, I wish I could have gotten a better deal when I sold the joint. If I had only known…"Hal failed to find any of that unbelievable. "Well, at least it made someone some money," Hal lamented. "Do you have any idea who they sold it to?""Well now, here's the crazy part," Victor paused before drawing a breath. "There was this up and coming software company around that time that rhymes with Bike-rosoft that was eager to get their hands on it. They took what you made and it became the core of a little program called Excel."Hal instantly started to regret reuniting with Victor. Whether he was full of crap or not, Hal's resentment came flooding back during the rest of their lunch together. He made an excuse to leave right after the check came, hoping to avoid something like Victor claiming he helped Al Gore create the internet. [Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!
Error'd: Every System's Preferences
Rob W. wrote, "Looks more like this process is responsible for customizing the entire solar system's preferences."
CodeSOD: Sorting Out a Late Night
Karl’s trials of crunch (previously) didn’t end with a badly written brain-fart. After too many consecutive late nights, Karl noticed that their grid layout was wrong.It did this:
How The Semester Ends
Ginger recently finished an advanced degree, and during her work, she of course had to work as a TA for a number of classes. Computer science professors are, at least in theory, capable of programming, and thus can build automation around assignments- providing students with templates to highlight specific tools and techniques, or to automate the process of grading.Dr. Buchler taught the computer graphics course, and the ultimate assignment was to build a simple 3D game. Buchler provided a pre-scaffolded project with a set of templates that could be filled in, so the students didn’t need to worry about a lot of the boilerplate. Beyond that, Buchler didn’t offer much guidance about how students should collaborate, so students did what came naturally: they set up git repos and shared code that way.The students who used Git, which was essentially all of them, started contacting Ginger. “My code is broken!” “It worked, on my machine when I wrote it, but now it doesn’t! I haven’t changed anything!”Obviously, there must be an issue with the professor’s template, but when Ginger mentioned this to Buchler, he dismissed the concern. “I’ve been using this template for years, and have never had a problem. The students must have errors in their code.”Ginger worked closely with one of the student groups, and if there were errors in the code, she couldn’t see them. And what immediately leapt out to her was that code which worked would suddenly break- but it only seemed like it happened after a commit.The core pattern was that the students would write a fragment of a shader, and then the project would merge their fragment with a surrounding template to create a full GLSL shader that could actually execute, akin to how Shader Toy injects some additional code around your key logic.Now, when loading code into the template, Buchler had written something like this: String[] vscr = new Scanner(Paths.get(ShaderProgram.class.getResource(shader).toURI())).useDelimiter("\\Z").next().split("\r\n");There was no real reason for the split, but Buchler wanted to use an array of lines instead of a blob of text. That was also the source of the problem.The split would remove Windows line endings from the students’ code. For the students, who were frequently on Windows, this meant that when their shader got loaded, all the newlines would get stripped from their code.This meant a simple shader, like:
CodeSOD: Assert Yourself
Chris V does compliance testing. This often means they trace through logic in code to ensure that very specific conditions about the code’s behavior and logic are met. This creates unusual situations, where they might have access to specific and relevant pieces of code, but not the entire codebase. If they spot something unusual, but not within the boundaries of their compliance tests, they just pass on by it.One of the C++ code bases Chris had to go through featured this “defensive” pattern everywhere.
CodeSOD: One Way to Solve a Bug
Startups go through a number of phases, and one specific phase is the transition from "just get it done and worry about the consequences tomorrow" into "wait, maybe if we actually did some planning and put some process around what we do, we won't constantly be one step behind the current disaster."And that's when they start to hire people who have more management experience, but are also technical enough that they can contribute to the product directly. At BK's company, the latest hire in that category is Sylvester.Sylvester is the new team lead, and he comes from a more "enterprise" background, which means he's had a very difficult time getting up to speed, and is unwilling or uncomfortable to make decisions with limited information. And also, Sylvester might not be particularly good at the job.BK noticed that Sylvester had a commit sitting in code review, and it had been sitting there for some time, so they took a look. One of the first things they spotted was a method called SolveBug, which made it clear they were in for a "treat".
Error'd: Watch the Skies!
"In light of the imminent UFO strike, I may need to reconsider my flight plans...or leaving my house in general," writes Pedro.
CodeSOD: Overlapping Complexity
After his boss left the company, Joel C was promoted to team lead. This meant that Joel was not only responsible for their rather large production codebase, but also for interviewing new potential team members. There are a ton of coding questions that one can ask in a technical interview, and Joel figured he should ask one that they actually solve in their application: given two unordered sets of timestamps, calculate how much overlap (if any) is between the two series.If you think about it for a minute, it's really quite simple: first, find the minimum and maximum values for each set to get the start and end times (e.g. [01:08:01,01:09:55] and [01:04:11,01:09:42]). Then, subtract the later start time (01:08:01) from the earlier end time (01:09:42) to get the overlap (01:09:42 - 01:08:01 = 00:01:41). A non-positive result would indicate there's no overlap (such as 12:00:04 - 13:11:43), and in that case, it should probably just be zero. Or, in a single line of code:
The Most Secure Option
“The auditors have finished examining our codebase.”That was how Randy’s boss started the meeting, and she delivered the line like a doctor who just got the tests back, and is trying to break the news gently.After someone in another department did the whole “I found a thumb drive in the parking lot, let me plug it into my work laptop!” thing, management realized that they hadn’t done any kind of security evaluation in years, and brought in a bunch of highly paid consultants to evaluate their practices. Part of that meant doing audits of their software portfolio for compliance with the new security standards.Now, Randy’s boss was running a cross-functional meeting- developers, operations, and even a few support desk representatives, to review the audit results. Most of the hits they took on the audit were the kind of slipshod stuff that accrues over years of under-budgeted, over-specced projects. Passwords stored in source control. A few SQL injection vulns. But the one that seemed like an easy win was the fact that they didn’t use any SSL on their web applications.“Oh, we should be able to fix that, easy,” Randy said.“Oh, we should, should we?” Benny, the sysadmin said. He leaned over the table, with his hands clasped. “How many SSL certs have you provisoned?”“Well, a bunch, I’ve-”“Because I have, and it’s no walk in the park, and it’s very expensive.”Randy blinked, and glanced over at his boss. She didn’t have anything to add.“That’s… not true?” Randy said. “It’s not that expensive to buy a cert, but we can also go with LetsEncrypt, which is free.”“Ah ha!” Benny said. “It’s very expensive to do it right. You can’t just use some service from the Internet. We’re here to talk about our security audit, and using LetsEncrypt is not possible. Anything hosted externally and accessible via the Internet poses a huge organizational risk. Free SSL from the Internet is an easy target for a hacker.”“Right,” Randy’s boss said. “We’ll table this for now, but it looks like we probably won’t add SSL until we have a better sense of the costs.”“My advice is that we don’t use SSL at all,” Benny said. “That will be more secure than what Randy’s proposing.”The audit happened early this year. No one has yet formulated a plan to move to SSL. [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
Representative Line: Time Dilation
A good variable name is clear and specific about what the variable does. But sometimes you can have a variable name that's perhaps a little too specific. Victoria found this representative line of Rust code:
CodeSOD: A Botched Escape
Nancy was recently handed a pile of "modern" PHP that weighs in at tens of thousands of lines of code.This is how every query is executed:
Error'd: Airport via TCP
Peter G. writes, "Luggage from flight SQ978 arriving from Singapore on belt 12. Luggage from PQ968 arriving from Ko Samui on belt 6. Packets from VNC arriving from Kazakhstan on port 5900"
What Lives Beyond the Blue Screen (2019)
As promised in the sneak peak, we have a very special Halloween feature planned for today! What Lives Beyond the Blue Screen is an animated story by Lorne Kates (voiced by Jack Rhysider), made in collaboration with our new friends at Human Readable Magazine:An everyday programmer decides to clean up the mess of his company's infrastructure before the big merger only to accidentally run the wrong command on the wrong location. Join the adventure as they rush to fix the mistake before they bring down the entire company.This will be you live-streamed premier, in just a few hours, at 1:00PM Eastern. Stay tuned!About Human Readable MagazineWe’re able to bring this to you thanks to Panagiotis “Pek” Peikidis. In addition to having an even more Greek name than mine, Pek is embarking on a remarkably awesome – and a bit insane – journey. He’s launching Human Readable Magazine: an actual paper magazine (available digitally too) that will take developers on technical deep dives to expand and challenge their knowledge of programming every month.It’s a kickstarter project that you should all go check out. Pek was inspired to start this after finding a lot of success with Morning Cup of Coding, a newsletter that shares programming articles from every field of programming.Creating quality content isn’t easy, but from what I’ve seen from Issue 0 Preview, and the creativity in the upcoming Halloween collaboration, Pek is up for the challenge. With our support, we can help make Human Readable Magazine a fixture of the programming community and have a lot more fun collaborations in the future. [Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today!
CodeSOD: Tern Down Service
In C, it’s not uncommon to define a macro like this one:#define MIN(a,b) (a>b?b:a)It’s useful to be able to quickly find the smallest of two numbers, and it’s useful to do that with something a bit more readable than a ternary.Of course, if you need to expand this to larger sets of numbers, it gets tricky. For example, maybe you need to find the smallest of three numbers.Agripina recently had to track down some strange behaviors in an IoT device, and found this stack of ternaries:
Once Bitten, Twice Tested
Blake had recently been hired as a software tester, tasked with testing the company's product on the latest operating system, Windows 2000. After running through his battery of tests, he informed management that he hadn't encountered any issues, and the product was dubbed Windows 2000-ready. During the next several weeks, the product was smoothly deployed by customers—until an installer bug report came in."Did you test the desktop shortcut after installing on Windows 2000?" Blake's manager, Sammy, asked from the threshold of Blake's cube."Yeah, I'm sure I did," Blake replied."A customer emailed us to say that when he chooses to add the desktop shortcut while installing, it causes a Blue Screen of Death," Sammy explained. "It happens consistently for him. The only way he can install successfully is to not choose the desktop shortcut option, which he calls 'unacceptable from an IT security standpoint.'"Blake frowned in confusion. "Security?""I know, it's weird," Sammy said. "I want to question him further on that point. In the meantime, I'd like for you to start looking into this."The first step was to reproduce the problem in-house. Blake was sure he would fail; he was absolutely certain that he'd already tested what was allegedly crashing. His first move was to install the product on a fresh Windows 2000 box. He checked the "Add a desktop shortcut" option, and after a few moments, the installer completed with no errors. A shortcut to run the program now sat on the desktop. Double-clicking the icon opened the program flawlessly.From there, Blake uninstalled and reinstalled the program. Yet again, no issues. Trying a different Windows 2000 PC was fruitless. Out of desperation, he even tried installing on Windows 98. In no case did a BSOD ever occur."I can't reproduce this bug," Blake told Sammy the next time the two were able to meet up in the latter's office. "The installer doesn't crash the system, and the desktop shortcut works fine. Is there something I'm missing?""Well, I just got some more info from the customer," Sammy said, with world-weariness bearing down upon him. "Did you try installing to the desktop?""Yes, I installed the desktop shortcut. Many, many times.""No, not the shortcut. I mean, install to the desktop.""To the desktop?" Blake repeated, frowning."The customer's corporate security policy considers program shortcuts untrustworthy. They fear they could be pointing to anything," Sammy explained. "To avoid any sort of issue along those lines, the customer is required to install all of his programs into separate folders on the desktop."Blake's jaw fell. "What?!"Sammy shrugged helplessly. "First they want to install shortcuts, now they don't trust shortcuts. I don't get it, either, but it doesn't matter. It should be possible to install our software into any valid folder without a BSOD. Go see if you can dupe this now."Blake slinked back to his desk. Much to his chagrin, he was able to reproduce the crash. Upon further investigation, it was discovered that the installer could crash the OS if one tried to install to a new folder on the desktop or in the user's Documents folder. Blake received a scolding from Sammy for missing this the first time around.It was a lesson well learned. In the years that followed, Blake strove to test every possible scenario, every fringe use case, every baffling type of input data that he could think of. Upon submitting his bug reports, he heard the occasional bemused comment from the developers: "Who in the real world would ever do that?"Blake would merely chuckle to himself, remembering the desktop shortcut. [TDWTF Survey Reminder] Don't miss your chance to tell managers what you REALLY think about good (and WTF-worthy) dev mentorship. You might win a TDWTF mug for participating!
CodeSOD: To Be Random Enough
A long time ago, when I was first learning about databases, one of the points brought up was the difference between a "natural key" and a "surrogate key". A natural key was a unique identifier which already existed in your dataset, and surrogate keys were those you made up- UUIDs or sequences or what have you.As a best practice, even if you have a viable natural key, you should still use a surrogate key. There are exceptions, but it's usually preferable to employ a database key which you control to provide identity, especially one which has no meaning- because that means it'll never need to change values.Adam H's co-worker never got this memo.They needed to store data about vehicles. The particular data being stored, in this case, was also time series data. So they decided that their key would be a mashup of the timestamp and the vehicle's 6-digit license plate number.There were a number of problems with this: not every record entered into this table was actually tied directly to a vehicle, so sometimes the license plate number was blank. The developer needed to avoid any key collisions, so they decided to randomly generate a value, which was hopefully "random enough".
Error'd: Errors on the Go!
"These adertisers are getting smarter. Picture ads of 'one weird trick doctors hate people are doing in Yourcity, USA' are on the outs. On the other hand...Mysterious blocks of JavaScript? You have my attention...," Angela A. writes.
Announcements: Sneak Peak: What Lives Beyond the Blue Screen
I’m totally stoked for what we have brewing for Halloween. It’s called What Lives Beyond the Blue Screen, and we’ve got a fun sneak peak for you:We’re able to bring this to you thanks to Panagiotis “Pek” Peikidis. In addition to having an even more Greek name than mine, Pek is embarking on a remarkably awesome – and a bit insane – journey. He’s launching Human Readable Magazine: an actual paper magazine (available digitally too) that will take developers on technical deep dives to expand and challenge their knowledge of programming every month.It’s a kickstarter project that you should all go check out. Pek was inspired to start this after finding a lot of success with Morning Cup of Coding, a newsletter that shares programming articles from every field of programming.Creating quality content isn’t easy, but from what I’ve seen from Issue 0 Preview, and the creativity in the upcoming Halloween collaboration, Pek is up for the challenge. With our support, we can help make Human Readable Magazine a fixture of the programming community and have a lot more fun collaborations in the future.In the mean time, stay tuned… What Lives Beyond the Blue Screen is coming next week!
CodeSOD: Enumerating Your Failures
Rick was recently looking at some code from another team at his company. He noticed something odd in the code, so he pinged the team lead, Linda. “Did you spot this?”“Oh, crap no,” Linda replied. “I should have caught this in code review, but I gotta be honest, Teddy is a bit… well, let’s just say I really should have caught that since I knew it was a Teddy commit.”Rick didn’t know much about Teddy, beside the fact that Teddy had a few years of experience. Certainly, he had enough experience to be familiar with Java programming, like working with enums and working with unit tests. Unfortunately, he doesn’t seem to understand them.
Announcements: First Annual Developer Mentorship Survey
Nearly fifteen years ago, I wrote Pounding A Nail: Old Shoe or Glass Bottle?. It opened by asking how one might respond to the following question:
Counting on Common Sense
Matt enjoyed teaching. He mentored junior devs and interns with no technological backgrounds, and helped them to be experienced programmers. He believed that employers should hire based on attitude and then train employees up on skills.That was before he met Derrick.Matt wasn’t entirely clear on how Derrick became an junior dev at their company. Maybe he was pushed by his parents or grandparents to get into that “new tech field”, or maybe he was someone’s son, or a family friend of an executive.To say that Derrick lacks technical experience is an understatement. Matt’s seen Amish farmers at the local market with a better understanding of programming. He proudly uses an antique flip phone, because that way the government can’t track him. The company uses two factor authentication via an app, and bought him a phone which supports the app. He leaves the phone at his desk and only uses it to log in. He writes code in Notepad where possible, because it’s installed on every computer and anything else is just excess.Worst, Derrick was mostly good natured and wanted to help, but didn’t understand why he needed mentoring and guidance.Most recently, Matt was trying to introduce Derrick to the life of being “full stack”, which is to say- getting data from the back end and building a report on the front end. In this case, it was a marketing report for tracking clicks related to a marketing campaign.It’s been rough going. While reviewing a recent changeset, Matt spotted a problem and messaged Derrick on Slack. “Hey, Derrick, that new module you just delivered? You added a bunch of count fields, but you’ve made them all text fields. Can you change them to be numeric? They’re counts, so they can’t be anything else.”“Sure, Matt,” Derrick replied, “but hey, not to get down on your mentoring, but you really ought to specify these things precisely.”Matt nearly choked on his coffee, internally screaming, “are you serious?” Matt cursed to himself and then gave himself 15 minutes to cool down, before replying back.“Sorry, Derrick,” Matt typed, “but I forget you may not be aware of the standards that are employed…” Matt typed everywhere, but decided to be more subtle, and replaced it with, “…here. But usually, if something is a type of number, we keep it as that numeric type. Sometimes this is an integer, a float, a decimal. If you have any questions, feel free to ask me. For now, can you change the text field to integers? We are counting clicks, so those are integers.”“Yeah, okay,” Derrick responded. “I’ll make them numbers.”An hour later, Derrick submitted another changeset.“Hey, Derrick,” Matt messaged again, “Those count fields you set as numbers. They seem to be floating point numbers. Could you change them to integers? They’re counts. Some of the summaries are showing rounding errors- 4.99999997, etc.”“Yeah, sure thing, Matt,” Derrick replied. “But hey, you really ought to specify these things precisely.”In a fit of restraint, Matt did not quote his earlier message requesting that Derrick use integers. Matt knew he could count on many things, but the one thing he couldn’t count on was Derrick. [Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!
CodeSOD: A Select System Call
Way back in the 90s, in an era when Swedish pop bands were getting regular US radio play and CVS was the optimal source control system, Alan worked on a remote-execution service for a “Unix-like” OS. One of his co-workers had just left the company, and Alan needed to track down a bug in a module which the co-worker had more-or-less owned during their tenure.The specific block of C code in question looked roughly like this:
CodeSOD: How Would You Rate Your Experience
The last time I was traveling, I noticed a little stand just past the security checkpoint, asking me to rate my experience. The five buttons ranged from a red frowny face to a green smiley, giving me the ability to respond with what must be the full range of human emotion. Every time I see one of those kiosks, I have to wonder: who uses those things, and who actually looks at the data?Perhaps inspired by that kiosk, Peter's company does something similar. There's a Slack bot which messages each employee every two weeks to get them to evaluate, on a scale of 1-5, how good a certain aspect of their job is. That data gets collected up onto a Google Sheets dashboard. And yes, the Google Sheet is both the datastore and the dashboard, which isn't surprising at all.Now, if you're using a regular old SQL database, you know that you shouldn't manually construct SQL strings, and instead use prepared statements, etc. to manipulate the data. But what if a spreadsheet is your database? Well, those rules go out the window, as this Scala block demonstrates:
Error'd: Encoded for YOUR Benefit
"Oracle makes it easy! Just dereference this pointer to view your failed invoice," wrote Jeremy W.
CodeSOD: A Context for Logging
When logging in Java, especially frameworks like Spring, making sure the logging statement has access to the full context of the operation in flight is important. Instead of spamming piles of logging statements in your business logic, you can use a “mapped diagnostic context” to cache useful bits of information during an operation, such that any logging statement can access it.One of the tools for this is the “Mapped Data Context”, MDC. Essentially, it’s very much like a great big hash map that happens to be thread-local and is meant to be used by the logging framework. It’s a global-ish variable, but without the worst side effects of being global.And you know people just love to use global variables.Lothar was trying to figure out some weird requests coming out of an API, and needed to know where certain session ID values were coming from. There are a lot of “correct” ways to store session information in your Java Spring applications, and he assumed that was how they were storing those things. Lothar was wrong.He provided this anonymized/generalized example of how pretty much every one of their REST request methods looked:
CodeSOD: The Replacements
Nobody wants to have a Bobby Tables moment in their database. So we need to to sanitize our inputs. Ted C noticed a bunch of stored procedures which contained lines like this:
CodeSOD: Cast Away
The accountants at Gary's company had a problem: sometimes, when they wanted to check the price to ship a carton of product, that price was zero. No one had, as of yet, actually shipped product for free, but they needed to understand why certain cartons were showing up as having zero cost.The table which tracks this, CartonFee, has three fields: ID, Carton, and Cost. Carton names are unique, and things like 12x3x6, or Box1, or even Large box. So, given a carton name, it should be pretty easy to update the cost, yes? The stored procedure which does this, spQuickBooks_UpdateCartonCost should be pretty simple.
CodeSOD: I See What Happened
Graham picked up a ticket regarding their password system. It seemed that several users had tried to put in a perfectly valid password, according to the rules, but it was rejected.Graham's first step was to attempt to replicate on his own, but couldn't do it. So he followed up with one of the end users, and got them to reveal the password they had tried to use. That allowed him to trigger the bug, so he dug into the debugger to find the root cause.
Error'd: The WTF Experience
"As it turns out, they've actually been singing Purple Haze before the start of all of those sportsball games," Adam writes.
CodeSOD: Parse, Parse Again
Sometimes, a block of terrible code exists for a good reason. Usually, it exists because someone was lazy or incompetent, which while not a good reason, at least makes sense. Sometimes, it exists for a stupid reason.Janet’s company recently bought another company, and now the new company had to be integrated into their IT operations. One of the little, tiny, minuscule known-issues in the new company’s system was that their logging was mis-configured. Instead of putting a new-line after each logging message, it put only a single space.That tiny problem was a little bit larger, as each log message was a JSON object. The whole point of logging out a single JSON document per line was that it would be easy to parse/understand the log messages, but since they were all on a single line, it was impossible to just do that.The developers at the acquired company were left with a choice: they could fix the glitch in the logging system so that it output a newline after each message, or they could just live with this. For some reason, they decided to live with it, and they came up with this solution for parsing the log files:
Coded Smorgasbord: Driven to Substraction
Deon (previously) has some good news. His contract at Initrode is over, and he’s on his way out the door. But before he goes, he wants to share more of his pain with us.You may remember that the StringManager class had a bunch of data type conversions to numbers and dates. Well guess what, there’s also a DateManager class, which is another 1600 lines of methods to handle dates.As you might expect, there are a pile of re-invented conversion and parsing methods which do the same thing as the built-in methods. But there’s also utility methods to help us handle date-related operations.
CodeSOD: Compiled Correctly
Properly used, version history can easily help you track down and identify the source of a bug. Improperly used, it still can. As previously established, the chief architect Dana works with has some issues with source control.Dana works on a large, complex embedded system. “Suddenly”, her team started to spot huge piles of memory corruption problems. Something was misbehaving, but it was hard to see exactly what.They ported Valgrind to their platform, just so they could try and figure out what was going wrong. Eventually, they tracked the problem down to a pair of objects.In the flow of the code, the correct path was that object A, which we’ll call Monster would be allocated. Then a second object would be allocated. Somehow, Monster instances were corrupting the memory of the second object.How does an object allocated earlier corrupt the memory of an object allocated later? Well, “before” and “after” have different meaning when your code is multi-threaded, which this was. Worse, the Monster class was katamari of functionality rolled up across thousands of lines of code. Obviously, there had to be a race condition- but a quick glance at all the Monster methods showed that they were using a mutex to avoid the race condition.Or were they? Dana looked more closely. One of the methods called during the initialization process, doSomething, was marked const. In C++, that should mean that the method doesn’t change any property values. But if it doesn’t change any property values, how can it lock the mutex?This is where walking through the commit history tells a story. “Fortunately” this was before Jerry learned you could amend a commit, so each step of his attempts to get the code to compile are recorded for posterity.The chain of commits started with one labeled “Add Feature $X”, and our doSomething method looked like this.
CodeSOD: Generically Bad
The first two major releases of the .NET Framework, 1.0 and 1.1 were… not good. It's so long ago now that they're easily forgotten, but it's important to remember that a lot of core language features weren't in the framework until .NET 2.0.Like generics. Generics haven't always been part of the language, but they've been in the language since 2006. The hope would be that, in the course of 13 years, developers would learn to use this feature.Russell F (recently) has a co-worker who is still working on it.
Error'd: An Error Storm of Monstrous Proportions
"Move over NOAA, Google News shows us, unfortunately after the fact that The Daily Beast is the TRUEST hurricane prognosticator," Alejandro D. writes.
The Windows Update
Every change breaks someones workflow.A few years ago, Ian started at one of the many investment banks based out of London. This particular bank was quite proud of how they integrated “the latest technology” into all their processes, “favoring the bleeding edge,” and “are always focusing on Agile methods, and cross-functional collaboration.”That last bit is why every software developer was on a tech support rotation. Every two weeks, they’d have to spend a day sitting with the end users, watching them work. Ostensibly, by seeing how the software was actually used, the developers would have a better sense of the users’ needs. In practice, they mostly showed people how to delete emails or recover files from the recycling bin.Unfortunately, these end users also directly or indirectly controlled the bank’s budgeting process, so keeping them happy was a big part of ensuring continued employment. Not just service, but service with a smile- or else.Ian’s problem customer was Jacob. Jacob had been with the bank at least thirty years, and still longed for the days of lunchtime brandy and casual sexual harassment. He did not like computers. He did not like the people who serviced his computer. He did not like it when a web page displayed incorrectly, and he especially did not like it when you explained that you couldn’t edit the web page you didn’t own, and couldn’t tell Microsoft to change Internet Explorer to work with that particular website.“I understand you smart technical kids are just a cost of doing business,” Jacob would often say, “but your budget is out of control. Something must be done!”Various IT projects proceeded apace. Jacob continued to try and cut their budget. And then the Windows 7 rollout happened.This was a massive effort. They had been on Windows XP. A variety of intranet and proprietary applications didn’t work on Windows 7, and needed to be upgraded. Even with those upgrades, everyone knew that there would be more problems. These big changes never came without unexpected side effects.The day Jacob got Windows 7 imaged onto his computer also happened to be the day Ian was on helldesk duty. Ian got a frantic email:
CodeSOD: An Updated Version
Some folks were perplexed by the fact that Microsoft skipped Windows 9 and went straight to Windows 10. The urban legend is that so many old applications checked which version of Windows was running by doing something like version.startsWith("Windows 9") to see if they were on 95 or 98, that Microsoft risked breaking otherwise working code if they released Windows 9.But gone are those days of doing string munging to check which version of an OS we’re running on. We’ve got much better ways to check what features and functionality are available without having to parse strings out, right?John D found some TypeScript code in a Ionic app that needs to adapt to different versions of iOS:
When Unique Isn't Unique
Gather 'round, young'uns, for a tale from the Dark Ages of mobile programming: the days before the iPhone launched. Despite what Apple might have you believe, the iPhone wasn't the first portable computing device. Today's submitter, Jack, was working for a company that streamed music to these non-iPhone devices, such as the Palm Treo or the Samsung Blackjack. As launch day approached for the new client for Windows Mobile 6, our submitter realized that he'd yet to try the client on a non-phone device (called a PDA, for those of you too young to recall). So he tracked down an HP iPaq on eBay just so he could verify that it worked on a device without the phone API.The device arrived a few days out from launch, after QA had already approved the build on other devices. It should've been a quick test: sideload the app, stream a few tracks, log in, log out. But when Jack opened the app for the first time on the new device, it was already logged into someone's account! He closed it and relaunched, only to find himself in a different, also inappropriate account. What on earth?!The only thing Jack could find in common between the users he was logged in as was that they were running the same model of PDA. That was the crucial key to resolving the issue. To distinguish which device was making the calls to the streaming service, Jack used a call in Windows Mobile that would return a unique ID for each mobile device. In most devices, it would base this identifier on the IMEI, ensuring uniqueness—but not on the HP iPaq. All HP devices could automatically log into the account of the most recently used iPaq, providing the user logged out and back in, as it would generate a recent-user record with the device ID.Jack had read the documentation many times, and it always stated that the ID was guaranteed to be unique. Either HP had a different definition of "unique" than anyone else, or they had a major security bug!Jack emailed HP, but they had no plans to fix the issue, so he had to whip up an alternate method of generating a UUID in the case that the user was on this device. The launch had to be pushed back to accommodate it, but the hole was plugged, and life went on as usual. [Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!
CodeSOD: Butting In
Initech is a large, international corporation. Any time you're doing business at a global scale, you're going to need to contend with a language barrier sooner or later. This makes employees who are multilingual valuable.Dana recently joined Initech, and in the first week, was warned about Jerry. Jerry was the "chief" "architect" and team "lead", and was one of those special, valuable employees who spoke three languages. Correction, "spoke" needs scare quotes too, because Jerry was incomprehensible in every language he spoke, including his native tongue.Jerry's emails were stuff of legend around the office. Punctuation was included, not to structure sentences, but as a kind of decoration, just to spice up his communiques. Capitalization was applied at random. Sentences weren't there to communicate a single thought or idea, but to express fragments of half considered dreams.Despite being the "chief architect", Jerry's code was about as clear as his emails. His class definitions were rambling stretches of unrelated functionality, piled together into a ball of mud. Splattered through it all were blocks of commented out functionality. And 99.9% of his commits to master had syntax errors.Why did his commits always have syntax errors? Jerry had never seen fit to install a C++ compiler on his machine, and instead pushed to master and let their CI system compile and find all his syntax errors. He'd then amend the commit to fix the errors, and woe betide anyone else working in the repo, because he'd next git push --force the amended commit. Then he'd fix the new round of syntax errors.Their organization did have an official code review standard, but since no one understood any of Jerry's code, and Jerry was the "chief", Jerry reviewed his own code.So, let's talk about enumerated types. A common practice in C++ enums is to include an extra value in the enum, just to make it easy to discover the size of the enum, like so:
Error'd: Modern Customer Support
"It's interesting to consider that First Great Western's train personnel track on-time but meanwhile, their seats measure uptime," writes Roger G.
CodeSOD: Trim Off a Few Miles
I don’t know the length of Russell F’s commute. Presumably, the distance is measured in miles. Miles and miles. I say that, because of this block, which is written… with care.
CodeSOD: And it was Uphill Both Ways
Today’s submission is a little bit different. Kevin sends us some code where the real WTF is simply that… it still is in use somewhere. By the standards of its era, I’d actually say that the code is almost good. This is more of a little trip down memory lane, about the way web development used to work.Let’s start with the HTML snippet:
CodeSOD: Do You Need this
I’ve written an unfortunate amount of “useless” code in my career. In my personal experience, that’s code where I write it for a good reason at the time- like it’s a user request for a feature- but it turns out nobody actually needed or wanted that feature. Or, perhaps, if I’m being naughty, it’s a feature I want to implement just for the sake of doing it, not because anybody asked for it.The code’s useless because it never actually gets used.Claude R found some code which got used a lot, but was useless from the moment it was coded. Scattered throughout the codebase were calls to getInstance(), as in, Task myTask = aTask.getInstance().At first glance, Claude didn’t think much of it. At second glance, Claude worried that there was some weird case of deep indirection where aTask wasn’t actually a concrete Task object and instead was a wrapper around some factory-instantiated concrete class or something. It didn’t seem likely, but this was Java, and a lot of Java code will follow patterns like that.So Claude took a third glance, and found some code that’s about as useful as a football bat.
Accounting for Changes
Sara works as a product manager for a piece of accounting software for a large, international company. As a product manager, Sara interacts with their internal customers- the accounting team- and Bradley is the one she always bumps heads with.Bradley's idea of a change request is to send a screenshot, with no context, and a short message, like "please fix", "please advise", or "this is wrong". It would take weeks of emails and, if they were lucky, a single phone call, for Sara's team to figure out what needs to be fixed, because Bradley is "too busy" to provide any more information.One day, Bradley sent a screenshot of their value added taxation subsystem, saying, "This is wrong. Please fix." The email was much longer, of course, but the rest of the email was Bradley's signature block, which included a long list of titles, certifications, a few "inspirational" quotes, and his full name.Sara replied. "Hi Brad," her email began- she had once called him "Bradley" which triggered his longest email to date, a screed about proper forms of address. "Thanks for notifying us about a possible issue. Can you help me figure out what's wrong? In your screen shot, I see SKU numbers, tax information, and shipping details."Bradley's reply was brief. "Yes."Sara sighed and picked up her phone. She called Bradley's firm, which landed her with an assistant, who tracked down another person, who asked another who got Bradley to confirm that the issue is that, in some cases, the Value Added Tax isn't using the right rate, as in some situations multiple rates have to be applied at the same time.It was a big update to their VAT rules. Sara managed to talk to some SMEs at her company to refine the requirements, contacted development, and got the modifications built in the next sprint."Hi, Bradley," Sara started her next email. "Thank you for bringing the VAT issue to our attention. Based on your description, we have implemented an update. We've pushed it to the User Acceptance Testing environment. After you sign off that the changes are correct, we will deploy it into production. Let me know if there are any issues with the update." The email included links to the UAT process document, the UAT test plan template, and all the other details that they always provided to guide the UAT process.A week later, Bradley sent an email. "It works." That was weird, as Bradley almost never signed off until he had pushed in a few unrelated changes. Still, she had the sign off. She attached the email to the ticket and once the changes were pushed to production, she closed the ticket.A few days later, the entire accounting team goes into a meltdown and starts filing support request after support request. One user submitted ten by himself- and that user was the CFO. This turns into a tense meeting between the CFO, Bradley, Sara, and Sara's boss."How did this change get released to production?"Sara pulled up the ticket. She showed the screenshots, referenced the specs, showed the development and QA test plans, and finally, the email from Bradley, declaring the software ready to go.The CFO turned to Bradley."Oh," Bradley said, "we weren't able to actually test it. We didn't have access to our test environment at all last week.""What?" Sara asked. "Why did you sign off on the change if you weren't able to test it!?""Well, we needed it to go live on Monday."After that, a new round of requirements gathering happened, and Sara's team was able to implement them. Bradley wasn't involved, and while he still works at the same company, he's been shifting around from position to position, trying to find the best fit… [Advertisement] Forget logs. Next time you're struggling to replicate error, crash and performance issues in your apps - Think Raygun! Installs in minutes. Learn more.
Error'd: Full Stack Languages...and BEYOND!
"When travelling to outer space, don't forget your...Javascript code?" writes Rob S.
Redesign By Committee
Carl was excited to join his first "real" company and immerse himself in the World of Business. The fresh-faced IT Analyst was immediately assigned to a "cross-strata implementation team" tasked with redesigning the RMA form completed by customers when they returned goods. The current form had been flagged for various weaknesses and omissions.The project's kickoff meeting ran for three hours, with twelve team members in attendance representing departments throughout the company. By the end of the meeting, the problem had been defined, and everyone had homework: to report to the next team meeting with their own interpretations of what the new form should look like.Each team member dutifully came back with at least one version of the form each. The next meeting consisted of Norman, the QA Manager, critiquing each prospective form as it was presented to the group. Without fail, he'd shake his head with a furrowed brow, muttering "No, no ..."This proceeded, form after form, until Terry, an Accounts Junior, presented his version. When Norman expressed displeasure, Terry dared to ask, "Well? What's wrong with it?"Norman gestured to the list of required criteria in his hands. "You've missed this piece of information, and that's probably the most important item we need to capture."Terry frowned. "But, Norman, your form doesn't have that information on it, either."Upon looking down at his own form, Norman realized Terry was correct. He rallied to save his dignity. "Ah, yes, but, you see, I know that it's missing."Stupefied, Terry backed down.Carl cycled through bafflement, boredom, and agony of the soul as the meeting dragged on. At one point, Finance Manager Kevin picked up yet another version of the form and asked, "What about this one, then?"Jason the Ops Manager skimmed through it, ticking off items against the list of criteria. "Yup, yup, yup, yup ... yes, this is it! I think we've cracked it!" he exclaimed.Norman peered at the form in Jason's hands. "That's the form we're currently using." The very form they needed to replace.Hours upon hours of combined effort had thus far resulted in no progress whatsoever. Carl glanced at the conference room's wall clock with its stubbornly slow hands, wondering if a camera hidden behind it were recording his reaction for a YouTube prank channel. But, no. He was simply immersed in the World of Business. [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
CodeSOD: You Can Take Care
Tiberrias sends us some code that, on its face, without any context, doesn’t look bad.
A Learning Experience
Jakob M. had the great pleasure of working as a System Administrator in a German school district. At times it was rewarding work. Most of the time it involved replacing keyboard keys mischievous children stole and scraping gum off of monitor screens. It wasn't always the students that gave him trouble though.Frau Fritzenberger was a cranky old math teacher at a Hauptschule near Frankfurt. Jakob regularly had to answer support calls she made for completely frivolous things. Having been teaching since before computers were a thing, she put up a fight for every new technology or program Jakob's department wanted to implement.Over the previous summer, a web-based grading system called NotenWertung was rolled out across the district's network. It would allow teachers to grade homework and post the scores online. They could work from anywhere, with any computer. There was even a limited mobile application. Students and parents could then get a notification and see them instantly. Frau Fritzenberger was predictably not impressed.She threw a fit on the first day of school and Jakob was dispatched to defuse it. "Why do we need computers for grading?!" she screeched at Jakob. "Paper works just fine like it has for decades! How else can I use blood red pen to shame them for everything they get wrong!""I understand your concern, Frau Fritzenberger," Jakob replied while making a 'calm down' gesture with his arms. "But we can't have you submitting grades on paper when the entire rest of the district is using NotenWertung." He had her sit down at the computer and gave her a For Dummies-type walkthrough. "There, it's easier than you think. You can even do this at night from the comfort of your own home," he assured her before getting up to leave.Just as he was exiting the classroom, he heard her shout, "If you were my student, I would smack you with my ruler!" Jakob brushed it off and left to answer a call about paper clips jammed in a PC fan.The next morning, Jakob got a rare direct call on his desk phone. It was Frau and she was in a rage. All he could make out between strings of aged German cuss words was "computer is broken!" He hung up and prepared to head to Frau's Hauptschule.Jakob expected to find that Frau didn't have a network connection, misplaced the shortcut to her browser, didn't realize the monitor was off, or something stupid like that. What he found was Frau's computer was literally broken. The LCD screen of her monitor was an elaborate spider web, her keyboard was cracked in half, and the PC tower looked like it had been run over on the Autobahn. Bits of the motherboard dangled outside the case, and the HDD swung from its cable. "Frau Fritzenberger... what in the name of God happened here?!""I told you the computer was broken!" Frau shouted while meanly pointing her crooked index finger at Jakob. "You told me I have to do grades on the computer. So I packed it up to take home on my scooter. It was too heavy for me to ride with it on back so I wiped out and it smashed all over the road! This is all your fault!"Jakob stared on in disbelief at the mangled hunks of metal and plastic. Apparently you can teach an old teacher new tricks but you can't teach her that the same web application can be accessed from any computer. [Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!
CodeSOD: Should I Do this? Depends.
One of the key differences between a true WTF and an ugly hack is a degree of self-awareness. It's not a WTF if you know it's a WTF. If you've been doing this job for a non-zero amount of time, you have had a moment where you have a solution, and you know it's wrong, you know you shouldn't do this, but by the gods, it works and you've got more important stuff to worry about right now, so you just do it.An anonymous submitter committed a sin, and has reached out to us for absolution.This is a case of "DevOps" hackery. They have one server with no Internet- one remote server with no Internet. Deploying software to a server you can't access physically or through the Internet is a challenge. They have a solution involving hopping through some other servers and bridging the network that lets them get the .deb package files within reach of the destination server.But that introduces a new problem: these packages have complex dependency chains and unless they're installed in the right order, it won't work. The correct solution would be to install a local package repository on the destination server, and let apt worry about resolving those dependencies.And in the long run, that's what our anonymous submitter promises to do. But they found themselves in a situation where they had more important things to worry about, and just needed to do it.
Error'd: Many Languages, One WTF
"It's as if IntelliJ IDEA just gave up trying to parse my code," writes John F.Henry D. writes, "If you have a phone in English but have it configured to recognize two different languages, simple requests sometimes morph into the weirdest things."
...21222324252627282930...