Skip to main content

Error'd: It's About Time

1 day 2 hours ago

Usually I have to save up a few weeks' worth of error'ds to get five of a kind, but this week we got a rash of funky date entries! I guess we were due.

First up Tim R. reminding us here that "Dates are difficult! ...but when the entire purpose of your web site is to convert the time to different time zones, I'm not inclined to give you much slack for being one hour out."

And an anonymous reader who just doesn't trust big tech. "In my calendar I have a monthly reminder to clear my data MS data manually. Now you know why, although I don't expect this will come as a surprise to anyone." Note the date on the lower right of the screenshot.

"June has 30 days, so 31 was not accepted," repeats Daniel D. incredulously. "I needed to calculate day difference between two dates. So I entered June 30 (as shown) only to get this error message. Now - should I trust that calculator to calculate date differences, what you say?"

Daniel D. went on to share with us a couple of images from "A well-known e-commerce website in Central Europe that allows you to filter by battery life! Only it randomly switches to seconds." Yes, randomly. See the second image too.

And finally this week, Marc Würth identified a novel Network Solutions Domain History Date Format(TM) "In other places, they displayed dates formatted as "01/13/2025", for example. I guess, instead of using actual ISO 8601, they just flipped the order and replaced the slashes with dashes."

[Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.
Lyle Seaman

Representative Line: Readable Formats

2 days 2 hours ago

We all love format strings for generating human readable text. Certainly, they're a better choice than string concatenation. Even if I have a blind spot that keeps me from remembering the printf format tokens, I still prefer to use format strings.

Jasmine has a co-worker that does use format strings, but they also miss using string concatenation. So they've found a way to combine them, and avoid the perils of making readable code that describes the format of their text.

myField.DataFormatString = "{0:#,##0." + new string('0', 2) + ";(#,##0." + new string('0', 2) + ")}";

Now, in their defense, I can see how this code started its life. At some point, they wanted to make the number of decimal places a parameter. And sure, this is an easy way to do that and retain the intent, though this whole thing could be cleaned up with just a simple decimalPlaces = new string('0', 2), which would make the concatenation less confusing to read.

Related, while I was checking the documentation on the .NET formatting strings, I learned that they have a per-mille format specifier which requires writing a unicode sigil on most keyboards.

I'm sorry, but seeing string perMilleFmt = "#0.## " + '\u2030'; in my code would be TRWTF.

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Remy Porter

CodeSOD: Doing the Assignment

3 days 2 hours ago

Today's code maybe isn't much of a WTF, but it does point in the general direction of, "Damn, you live like this?" Poor Nancy unfortunately does.

int x = 3; int y = 4; int z = 4; x = y = z;

Each variable is declared and initialized, and then they're set equal to each other. It just raises the question though, why do it this way? Why not declare them and then x = y = z = 4, if we want that? Or maybe, for more clarity, int x = DEFAULT_VALUE; would be more legible, and we can skip the multiple assignments on one line. Why does x get set to 3 but then overwritten?

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.
Remy Porter

The Outage

4 days 2 hours ago

At my employer, we use a service called Coveralls, which is a code coverage reporting tool that hooks into your CI pipeline. It takes your lcov reports and gives you some insights, and also makes it easy to cause the CI pipeline to fail if newly added code doesn't have reasonable coverage.

I have no strong feelings about the tool, but on February 24th, our CI jobs started failing, and our CI step that talked to Coveralls was the culprit. Coveralls had gone down. That happened to us, and a lot of other people. It was a widespread outage impacting anybody who used their service.

Coveralls actively published updates as the outage dragged on, and boy, did it drag on. Between them posting nearly identical updates minutes or even seconds apart and the general desperation that snuck into their outage notes after the first few days, I couldn't help but find their notes hilarious.

They've published their post-mortem, and the short version is that despite them paying their bills, Amazon decided they hadn't, and shut down their services. But it took them roughly 68 hours to figure that out.

If you scroll down past the post-mortem, you can see their outage notes. This is an unauthorized, dramatic reading of those notes. We've taken some liberties in interpreting it.

I hope this is taken in a good spirit, because they were just doing their best when this happened. I don't think most companies would be able to maintain operations when their cloud provider decides to lock their accounts. But I don't care who you are: begging your users to email you if they can help you migrate off AWS is funny.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
Remy Porter

A Vat of Terrible Experiences

5 days 2 hours ago

Taxes are a royal pain for everyone. Amazon has found a unique way to make them even worse, as Kris W. attests:

I recently bought a €9.61 kitchen knife on Amazon Spain. My card was charged €7.94 instead. After some investigation, I discovered that Amazon had applied an old VAT registration number I'd added to my personal account years ago, and had classified my purchase as a VAT-exempt intra-EU business transaction. The invoice even contained my business address from 2022, which no longer appeared anywhere in my account settings. I just wanted to remove the VAT number so I could go back to buying kitchen utensils without accidentally generating international tax paperwork.

Unfortunately, Amazon no longer provided any visible way to manage that VAT number. Their customer support chatbot insisted I provide the order number from which I wanted the VAT number removed. A human agent confidently explained that I must have entered it into a secondary address field, and instructed me to delete and recreate my shipping address. Another support representative sent me an extensive list of documents I'd need to provide, including my passport, airline boarding passes, proof of export outside the EU, or my NATO identification card. Apparently removing a VAT number from an Amazon account is a process normally reserved for international travelers, Andorran residents, and military alliances.

Eventually, I found Amazon's official help page. It explicitly stated that VAT numbers could be removed either by contacting Customer Service or by creating an Amazon Business account to use the self-service option. After another round of correspondence, Customer Service informed me that they were not allowed to remove VAT numbers and instructed me to use the Business settings that my personal account didn't have. So I followed the documentation and created a Business account using my existing email address. During registration, Amazon required me to enter the very VAT number I was trying to remove, then promptly congratulated me by email on successfully adding and activating it.

But I couldn't access the Business settings yet. Amazon couldn't verify my business and demanded official documentation, so I obtained two freshly-issued certificates from two separate Spanish government agencies to prove that I was, in fact, a self-employed software developer. I uploaded both documents and waited. Eventually, my shiny new Amazon Business account was approved. I now had a separate Business account, complete with its own purchasing features and complimentary Business Prime membership. At last, I could navigate to the promised VAT-management page!

The page displayed my VAT number, confirmed it was valid, and offered a button to add more tax information. Beside the existing number, however, there was no Edit button. No Delete button. No self-service removal option whatsoever. There was only a link saying, Contact Customer Service to change your tax ID.

Naturally, the link led to a generic help center. After creating an entire business account, submitting government paperwork, and successfully registering the same VAT number a second time, I had arrived precisely where I started: Customer Service, which had already explained that it was not allowed to remove VAT numbers.

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Ellis Morning

Error'd: Scrollpocalypse

1 week 1 day ago

Dr. Doom...scroller titled this one "Scrollbar-ception". Said he "Screenshot of the TikTok webpage (i.e. in a desktop browser) while not logged in. I swear this wasn't a NSFW TikTok video, instead it was a montage of some live show from some singer. Anyway... Back on the topic of the actual publishable snarky comments: Social media is known for doom-scrolling. Well, these are scrollbars of doom. Or doom-scrollbars."

An anonymous reader clarified "I was reorganizing the document by drag-and-dropping a bunch of table cells a bit too far for Word's comfort and it's telling me what I did wrong." Clearly.

B.J. H. reported a crisis. "First Southwest made me question the existence of my bags: I saw them scanned but the bag tracking system said there were no scans. Then the next page made me question my own existence as well." B.J. who?

Adam R. reported a new way of formatting numbers. "Stripe has decided "You know what, I'll put the +/- sign for the transaction amount on the *previous* line instead of the same line, just for funsies." Less snarkily: line break algorithms are fickle, and they forgot to put a non-breaking space in there."

Peter S. proposed "I was trying to sell my Peleton equipment on their official "Repowered" site, and I was shown this nice list of yes/no buttons. I am not sure if I feel like gambling today with these answers." I want to know if Peter is unloading all his equipment because he reached his goals, or if he just gave up.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
Lyle Seaman

The Frist Line of Defense

1 week 2 days ago

We don't cover a lot of security issues here, simply because they're not usually funny. But sometimes, they are. So here's a quick hit about some recent ones.

We start with a very bad month for the Danish social security system, the Central Register of Persons (CPR). Last week, they detected a breach which exposed the personal details of 8.8m people. Per the Register article, a cybersecurity specialist correctly pointed out that treating your ID number as if it were a secret was a terrible idea in the first place, but unfortunately, so many systems have grown up around the idea that full knowledge of your state issued ID number as proof of identity, that the security expert is screaming into the wind. They're right, but it's going to take a lot to change.

Okay, Denmark's social security service was hacked. What's so funny about that?

Well, the mechanism of the hack appears to go thusly. First, third party companies have access to the database, which they can use to send notifications to their customers via CPR. That connection is secured with a password, and one of those third parties secured their account with the kind of password you'd use to protect the precious air of the planet Druidia. Also known as the kind of password some idiot would put on their luggage: "123456". (paywalled, Danish article).

The hacker accessed the system on September 10th, and spent ten days searching through the system. The intrusion wasn't detected until October 2nd, when CPR went to send an invoice to the third party company and noticed, "Boy, that's more searches than they have customers." Now, obviously, CPR should have never even allowed such a low complexity password, but also, the third party company shouldn't have used such a low security password.

Now, if you'll excuse me, I have to change the combination on my luggage.

In other news, I'm not particularly fond of blockchain stuff. Mostly, the whole distributed ledger seems like a solution in search of problems, and "trading tokens as if they're money" is the best thing anybody's been able to come up with. Back in my consulting days, when blockchains were all over the news, I was consulting with a large retailer, and they were exploring using blockchain in their supply chain. "How does that work?" I asked innocently. "It'll have blockchain in it." "Sure, but what does the blockchain get you?" "We'll be using blockchain. If there's like, an e. coli outbreak, we can trace where it came from." "Couldn't you get that out of a regular database?" "But this'll have blockchain."

In any case, blockchain companies getting hacked and having all their users' assets stolen is practically a daily occurrence. Not really notable. But a recent hack is legitimately interesting.

A company, called Ledger, sells "hardware wallets". Instead of storing your keys on some third party's servers (where it'll get hacked and you'll lose all your "money"), you store them on a hardware device that you put in a safe. It's not connected to the internet, and thus is unhackable. Or so you'd think. But if enough people are buying those devices, a supply chain attack becomes potentially very lucrative. And that's exactly what happened. Someone in the supply chain cracked a bunch of these devices open, and inserted new hardware. They attached a microcontroller to the screen leads, that allowed it to read what was on the screen (and thus detect when the screen was displaying a recovery code that could be used to access the wallet), and a cellular modem that allowed it to literally phone home with that information.

In total, these hackers walked away with the equivalent of nearly $100M in cryptocurrency.

All the devices passed through Ledger, where they were inspected before being sold. Presumably, they were sealed with tamper-resistant packaging. It's plausible that the tamperer was downstream from here and the customers didn't fully inspect the packaging. Even your most savvy user generally doesn't check that kind of thing, and I suspect a lot of these customers aren't actually all that savvy. But also, companies in the crypto space tend to be... we'll say, more eager than cautious, so I wouldn't be surprised if the tampering happened upstream and didn't get caught by their inspection process.

Security is hard in the best case. It's much harder when you're putting the final onus of security on end users who may have thousands or even millions of dollars locked behind a single key. Or when passwords are hard, so you pick an easy one to remember.

[Advertisement] Plan Your .NET 9 Migration with Confidence
Your journey to .NET 9 is more than just one decision.Avoid migration migraines with the advice in this free guide. Download Free Guide Now!
Remy Porter

Representative Line: A Diamond in the Rough

1 week 3 days ago

Mandy's co-worker recently learned about virtual inheritance in C++. It's become their new favorite button to push, and they only use virtual inheritance.

Virtual inheritance is one workaround for the "diamond problem", where you have an inheritance tree that "recombines" via multiple inheritance: when a child class has a Hapsburg-esque parentage, it's hard to decide which inherited methods are being invoked or overridden.

In C++, imagine you have class A, which gets derived into classes B and C. Class D then uses multiple inheritance to inherit from B and C. In practice, this means that D inherits from A twice, and would have two internal copies of all of A's members.

If, on the other hand, you have B and C inherit virtually (class B : public virtual A), then class D will only actually inherit a single copy of A.

If you're reading this and going, "Boy, this just sounds like another reason to avoid multiple inheritance," you're probably right. The important thing, though, is inheriting virtually impacts how your child classes will inherit. It only matters if you have child classes.

Which brings us back to Mandy's co-worker. He read somewhere that defaulting to virtual inheritance all the time was safer, so he did that all the time. All. The. Time.

Including in this case:

class SomeSpecificDerivedClass final : public virtual SomeBaseClass

The class here is marked final. It can't be inherited from. The use of virtual accomplishes nothing.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
Remy Porter

Editor's Soapbox: Digital Mail

1 week 4 days ago

Ever get some special letter, card, or picture from a friend or loved one that you held onto, maybe even taped to your cube or office wall? Is it something you still look at fondly, something that lifts your spirits whenever you're down? Certainly, a thoughtful card or letter is much nicer than a thoughtful email.

Now imagine your special keepsake being scanned, censored, and converted into a digital file that you can only view from a tablet — assuming you can afford the fee to access the tablet. The original has been destroyed; it's gone forever. You'll never get to see or feel it in your hands.

It sounds almost too cruel, like something you'd find in a Fallout game. Unfortunately, it's reality for more and more people incarcerated in US prisons.

I've been writing to an incarcerated person for a while now myself. I find the process incredibly rewarding; I think about my friend all the time and wish them well. Unfortunately, the scanning and processing takes absolutely forever, so in a given year we only exchange 3 letters per side. The digitized files that I receive have names censored out of them; I have no idea what's removed from my letters before my friend receives them. For me, this is all too reminiscent of exchanging letters with my grandmother in Iran before she died. Agents there would straight-up open the envelope, confiscate any valuables inside, marker over anything they didn't like, then re-seal the envelope and send it back on its merry way.

Over 30 US states now digitize the mail passing in and out of prisons, relying on AI to judge what's kosher and what isn't. If you thought AI was great with resumes, just wait until you task it with threat detection! It's been working so well that one nonprofit organization had to change its name: the word fight, used in any context whatsoever, gets flagged.

Once mail is scanned, it's only accessible by tablets that have to be paid for. Incarcerated people are already nickled and dimed for a ridiculous number of things and surely don't need more fees.

It doesn't stop at mail, either. The latest tech is also being used to eliminate physical visitation. Because if there's anything the pandemic taught us, it's that nothing beats seeing your loved ones exclusively on a screen for years at a stretch.

The states justify these egregious measures by playing the drug card. They're necessary to stop drugs from entering the prisons. But these states stop short of providing evidence to show that these tech-facilitated practices are actually having the intended effect. Even if they magically solved drug trafficking forever, could any result truly justify the vast harm being inflicted upon incarcerated people, their families, and their friends? Physical mail and visitation are necessary lifelines and psychological boosts for those who might otherwise have nothing and no one to hold onto during an unimaginably difficult time of their lives.

Do I really have to explain the benefit of parents and children exchanging homework, letters, and pictures?

I'm angry about this on so many levels. If you are, too, here's some stuff we can do to fight work against this together:

  • Support prison abolition with your time, money, and/or IT superpowers. Forced prison labor is slavery. The entire punitive model is cruel, biased, and far less effective than approaches like restorative and community-based justice. Moving on is long overdue and the best way to make all of this stop.
  • Avoid working for companies that facilitate these practices. Tell your friends not to work for them, either. If you're stuck working for them for survival's sake, look for ways to enact positive change from the inside.
  • Spread the word of what's happening. Most people have no idea. Use your knowledge to educate technical and non-technical folks. They might want to do something about this, too.
  • Write to incarcerated people yourself. Like Bob Ross said, "Everybody needs a friend." Knowing there's someone in your corner who cares about you makes all the difference in the world. Sites like WriteAPrisoner.com will match you up with a pen pal.

A drop of water seems harmless, but get enough of those together and you carve out the Grand Canyon. If we all do something to help, however big or small, our massed effort becomes something powerful. As tech professionals, we are especially empowered to push back on these cruel and abusive practices. We must act now, before they move out of prisons and into mainstream society.

Do you want your post office to start doing this?

Sources:

  • Abandon All Connection, Ye Who Enter Here: Digitized Prison Mail as Repression and Surveillance
  • WEBINAR: Fighting for families: How advocates are resisting attacks on visitation and physical mail
  • Involuntary Servitude: How Prison Labor is Modern Day Slavery
  • Why Justice Systems Don't Always Deliver

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Ellis Morning

CodeSOD: A Type of Type Safety

1 week 5 days ago

For some godawful reason, people like to explain object oriented concepts via analogy to biological taxonomies. I suppose it's easy to understand an "is-a" relationship (a cat is a mammal), but the down side is you get a complex and increasingly leaky analogy that over-emphasizes the importance of inheritance.

That's not to slight Alan's choice of using it to anoymize today's code. It's just a broad frustration on my part.

In any case, Alan has been working in a C++ codebase that's written by people who maybe don't fully understand all the key object oriented concepts. That's why you get code like this:

/* * If possible, steal tentacle from the given animal. */ void Animal::StealTentacle(Animal *animal) { // only Octopus and Squid can have tentacles if (!IS_INSTANCE_OF(this, Octopus) && !IS_INSTANCE_OF(this, Squid)) { return; } Limb *limb = animal->mLimbs->GetFirstTentacle(); if (limb) { limb->AttachToAnimal(this); // . . .

This function takes a raw pointer to an Animal object. If that pointer is not an Octopus or a Squid, we bail. Otherwise, we're going to take its tentacle, and do stuff with it.

Now, this is a pretty clear example of the type switch anti-pattern. Instead of using the type system and polymorphism to enforce restrictions, we instead do runtime type checks.

But wait a second, what's going on in that IS_INSTANCE_OF?

// I've noticed that dynamic_cast always returns a valid result when // casting an "objectPointer" of type "className". // Try casting it to a [Organism *] to force it to work. (?) #define IS_INSTANCE_OF(objectPointer, className) ((bool) (dynamic_cast<className *>(((Organism *) objectPointer)) != NULL)) #define IS_MEMBER_OF(objectPointer, className) IS_INSTANCE_OF(objectPointer, className) // temporary macro alias

This code attempts to take an objectPointer and first, force it into a pointer to our base type (Organism), using a C-style cast. Now, in C++, C-style casts are a shorthand, and the compiler will, based on the context, attempt to do the best cast which fits the situation, starting with a const_cast (which only alters the constness of the type), and failing all the way up to a reinterpret_cast- which just ignores type information entirely and assumes you know what you're doing.

Which this developer clearly doesn't.

In any case, we pass the C-style cast result into the dynamic_cast function, which attempts to cast that pointer into an instance of className. If no such conversion is possible (because they're not part of the same inheritance hiercharcy), it returns NULL, which is what they're checking.

Their comment highlights their misunderstanding of the function; dynamic_cast can be used to crosscast. In other words, dynamic_cast<Dog*>(my_cat) will actually work, because (in this example) Dog* and Cat* share a common base.

From the docs:

Otherwise, if expression points/refers to a public base class subobject of the most derived object, and the type of the most derived object has an unambiguous and public base class of type Target, the result points/refers to the Target subobject of the most derived object. In other words, dynamic_cast can be used to crosscast (or side-cast) pointers/references, between two types derived from the same base.

You shouldn't be using dynamic cast to solve this problem. Hell, you sohuldn't be doing any of this in the first place!

In any case, in actual usage, the developers responsible do stuff like this:

if (IS_INSTANCE_OF(animal, Felid)) { Felid *cat = (Felid *) animal; // Yes another C-style cast - this time (hopefully) devolving to the same dynamic_cast hidden inside the expansion of the previous macro.

I love when a comment says "hopefully". "This hopefully does what I think it should do".

I'll let Alan summarize the problems:

Used prudently, the dynamic dispatch facility that object oriented languages provide their users can be a valuable tool for capturing the domain model in clean, elegant code. However, as even C++'s designer Bjarne Stroustrup acknowledged, in "The Design and Evolution of C++", the introduction of support for Run-Time Type Information makes it possible to spurn such assistance and write RTTI-based code for which a verdict of "combines the syntactic elegance of C with the run-time efficiency of Smalltalk" is just "too kind".

.comment { border: none; } [Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.
Remy Porter

Error'd: Fast Quick

2 weeks 1 day ago

Matias shared a standard sort of flubstituted fail-merge error'd; not really egregious, just routine. "I am {{emotionType}} to hear this."

And another mail-not-merged from Reinier B. "When the package from [SELLER] seemed to be lost in the mail, I was very [EMOTIONAL_STATE] with the refund of [AMOUNT]. I can now buy another [ITEM] instead."

Dave A. didn't care for this mail flub, though it's hardly egregious in my opinion. He suggested we just label it with "A short description of snarky comments."

"I've_missed_you_too" Willy wrote in response to this earnest email. "Long lasting relationships with car dealers are built on the personal touchÖ."

"This is a title" Peter said about a polyglot web page. "This is a comment."

[Advertisement] Plan Your .NET 9 Migration with Confidence
Your journey to .NET 9 is more than just one decision.Avoid migration migraines with the advice in this free guide. Download Free Guide Now!
Lyle Seaman

Racing Trains

2 weeks 2 days ago

Robert G sends us a WTF from the outside, but I think we can come up with some hypotheses about what actually happened.

Robert was traveling by train. For complicated train reasons, the car he was seated on was not actually scheduled to continue with the train he was booked to ride, the replacement car missed its scheduled arrival, and the result was that Robert was left at a station needing to rebook his travel.

Now, given that this is in a region of the world with a fairly robust train network, this represented a hiccup of thirty minutes in a many hour trip. Not a particularly big deal. But Robert didn't want to get stranded any longer than he had to, so he took out his phone, fired up the train company's app, and made sure he had a reservation on the next train. He got the confirmation, and grabbed a coffee while he waited.

Not quite thirty minutes later, Robert boarded the train and went towards his reserved seat. Another passenger approached from the opposite direction, and they met at the seat. "Excuse me," Robert said, "but I reserved this one."

"No, I reserved this one."

Being reasonable people, they both pulled out their phones and pulled up their apps. Sure enough, each one of them was confirmed for that seat. Since the email confirmation had more details than the app provided, they both pulled up the email. Same seat. Both confirmed. The timestamp of the reservation? The same, down to the second.

"I don't think the conductor will let us sit in each other's laps," the other passenger said.

As it turned out, there was enough room on the train that no lap sitting was required. Everyone got a seat, even if it wasn't the one they reserved.

But the story stuck with Robert. A major transit provider had a reservation system that clearly had a race condition. It seemed like the most basic example of race conditions too, the kind you're shown in college to explain the basic concept.

"Check if the seat is reserved, and if it's not, reserve it." Because that sequence isn't atomic, two different threads could do the check, see it's not reserved, and then reserve it. I suppose it's at least something that one reservation doesn't overwrite the other, which at least indicates that a reservation is its own record.

The real question is this: this has to happen with some frequency, so how has nobody fixed it?

The real answer: they probably just don't care, either because they literally don't care, or because their software is such a trashfire that this doesn't even rise to the top ten bugs. It's likely a mix of both.

[Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.
Remy Porter

CodeSOD: A Tool for You

2 weeks 3 days ago

A junior dev on the team had a simple question: in Java, how do I correctly read user input from the CLI and act on it?

Now, we can wonder about a junior dev not having such basic knowledge, but maybe they're new to Java specifically. Who knows. But Robert's team has a senior on it who "likes to mentor". This senior has strong opinions about how to write software, extreme confidence in those opinions, and has somehow been around the company long enough that he knows where the bodies are buried and no one will fire him.

Here's his sample application for reading input.

import java.nio.charset.StandardCharsets; import java.util.*; public class ScannerTool { public static void main(String[] args) { Map<Optional<Character>, Map.Entry<String, Boolean>> map = new HashMap<>(); map.put(Optional.of('A'), new AbstractMap.SimpleEntry<>("You entered A.", true)); map.put(Optional.of('B'), new AbstractMap.SimpleEntry<>("You entered B.", true)); map.put(Optional.empty(), new AbstractMap.SimpleEntry<>("You entered nothing.", false)); Optional<Character> input; do { System.out.println("Please enter A or B:"); } while (!map.getOrDefault((input = nextCharacter()), new AbstractMap.SimpleEntry<>("", false)) .getValue()); System.out.println(map.get(input).getKey()); } public static Optional<Character> nextCharacter() { String l = new Scanner(System.in, StandardCharsets.UTF_8).nextLine(); if (l != null && !l.isEmpty()) { return Optional.of(l.charAt(0)); } return Optional.empty(); } }

Look, I know Java is verbose, but this is entirely next level. Giving this to a junior has to constitute an attempt to drive the youth out of the industry, because any sane person being told, "your job is to write this" would realize they've committed a grave error in their career choice and needs to escape now.

nextCharacter in this case actually returns the first character of the next line, not the next character. And if there isn't one, it returns an empty optional. Which, fine, we only expect one character per line of input for this exercise, so that's not wrong, I just don't like the name of the function.

Of course, using Scanner here is a wrecking ball fly swatter- that class is a full on parser for reading out common data types from a file. Worth showing to a junior, but a little out of scope of this question.

But the real overengineering is the map of maps- well, a map of map entries. The key to the outer map is an optional of the character that was entered by the user. The value is itself a map, the key of the map is the message we want to output, the value is whether or not the loop should continue. They've reinvented tuples using map entries. Which, in their defense, mainline Java doesn't have tuples (enterprise edition seems to have them in the javax namespace, but I'm not even certain those are meant to be general purpose tuples anyway). A quick search indicates that their absence is a perennial source of heated discussions in forums and Stack Overflow.

Robert writes:

It is remarkable in its creativity and execution and still has me in awe. When I tried to unpack it, my brain just started to pack up its things and left, haven't seen it since.

Bon voyage.

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Remy Porter

CodeSOD: A Random Article

2 weeks 4 days ago

Many years ago, DJ got his start doing odd web development jobs for a low hourly rate. He was only 19 when he got started, and what he lacked in experience he made up for in being cheap to hire.

As I said, that was many years ago, and he has since learned a lot. But he still has some code from his very first "someone paid me for this" project. This particular function needed to pick a random bit of content from their database to display in the "right side" banner area. This is how DJ implemented it.

// Create an array of all the ID's used $int = array(); $query = $sql->query("SELECT * FROM rightside"); while($row = $sql->objects('',$query)) { $int[ $row->id ] = $row->id; if ($row->id > $max) { $max = $row->id; } } // Find a random ID that has been used $x = false; while ($x == false) { $rand = rand(0,$max); foreach ($int as $thing) { if ($thing == $rand) { $x = true; } } } $query = $sql->query("SELECT * FROM rightside WHERE id = ".$rand);

We start by building an array. Then we query the database for all the content. We get all the rows and columns, butw e only are interested in one- the id. We create a sparse array, where the index of the item is the item's value. We also track the max.

Once we've got that, we start a loop. Inside that loop, we generate a random number, check if it's in our array by doing a foreach across the array, and if it is, we break the loop- we've found our random content. If it's not, we keep trying until we score a hit.

Finally, we construct our query with string concatenation and grab the content we want to display.

Now, as a true confession, there's an element of caveat emptor here; if you're hiring the kid from the local college and paying them a few bucks an hour, this is the kind of thing you get.

Is the code terrible? Yes, even by early-00s PHP standards. Is it really DJ's problem, though? No. I'd hope any of us would look back at the code we wrote when we were 19, and shudder. It means we've learned something in the interim.

For this confession, I say there's no need to atone. Hopefully everyone learned a lesson, especially the company trying to hire programmers on the cheap.

.comment { border: none; } [Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Remy Porter

CodeSOD: The Date and Time and Time

2 weeks 5 days ago

Today's anonymous submitter sends us some legacy Java code.

The task is this: check what time it is. And fortunately, even in the older Java datetime libraries that were terrible, this was an easy task. You just needed to do something like new Date(), which constructs a date time object set to the current time. getTime() picks off just the time portion.

Or, you could do this.

Timestamp current = new Timestamp(new Date().getTime()); Date date = new Date(current.getTime());

This creates a date, picks the time off, populates a timestamp, gets the time from the timestamp, and constructs a new date object.

The old Java date classes were awful, but they never needed you to do this. This is entirely home grown ugliness.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!
Remy Porter

Error'd: 12345

3 weeks 1 day ago

We have for you this week a full set of the Error'd we most love to hate: the perverse password policy.

An anonymous reader drops this, with little to say except to note "Speciaal passwords". Evidently they supplied a password which satisfied each of the five green critera, but still it was rejected. It would be nice to know where this offense originated,

Intrepid Michael R. explains "note: Handy is the German term for mobile phone (UK) or cell phone (US)."

Sacha R. observes a secret policy at play, saying "Oracle try to do the right thing by showing you the password policy requirements when you manually reset a password in their Fusion applications. It's just a pity that it doesn't show you the *correct* password policy requirements."

"Faith, here's an equivocator," reports Matthew S. "Pick one, Staples!" I bet it's the ampersand that offends.

"At least letters or numbers?" questions a final anon. "Just a little head scratching moment. After removing all special characters from the password I was able to register." This looks like partly a translation wtf and partly a software design wtf.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
Lyle Seaman

CodeSOD: Very Valid Tokens

3 weeks 2 days ago

Today's anonymous submitter shares with us the function their company uses to validate authentication tokens.

public bool IsTokenValid(string token) { //TODO return true; }

This is running in production. So that's fun. The user they've authenticated as is tracked separately at the start of their session, which makes it at least marginally harder to pretend to be someone you aren't, but for authentication, any token will do.

.comment { border: none; } [Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Remy Porter

CodeSOD: Quite a Distance from the Right Solution

3 weeks 3 days ago

Fritz's team needed to see if one point was within a certain distance from a center point. You or I would likely try and answer this question using a simple distance calculation, since that's the question we're trying to answer. But what if you didn't understand distances at all? Then you could write this little piece of genius.

private bool IsWithin(Point point, int radius) { for (int x = -radius; x < radius + 1; x++) { for (int y = -radius; y < radius + 1; y++) { if ((PositionX == point.X + x) && (PositionY == point.Y + y)) return true; } } return false; }

This limits us to integer point values, which itself is fine. This iterates across every coordinate from (x-radius,y-radius) to (x+radius,y+radius) and checks if any of them are equal to our center point, (PositionX,PositionY). Notably, this means we're not checking a radius, at least not in a traditional metric, we're checking a box (or using the taxicab metric). Which if we wanted to check a box, we actually have even easier math than the distance equation- we could do that with pure bounds checking.

I've never thought to try and brute force distance checking, and that feels like a failure of my own creativity. Fritz's team mate at least was able to WTF in a way I wouldn't have considered.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
Remy Porter

Representative Line: Unique Testing

3 weeks 4 days ago

Nikolai M's team had a flaky CI/CD build. About 0.5% of the time, one of their tests would fail: frequent enough to be annoying, but not so frequent that it motivated management to assign anybody to investigate. Nikolai eventually dug in, taking the initiative.

Microsoft's implementation of UUIDs calls them GUIDs. The GUID is, per the docs, really just a wrapper around UUID algorithms, and supports a variety of different UUID variants. I'm sure at some historical point, this wasnt't true, and Microsoft had some weird internal algorithm. That's not really here nor there, but the test that was failing was failing because of an assertion relating to GUIDs.

Assert.DoesNotContain("000", transactionId.ToString());

transactionId is a GUID. This line converts it to a string and checks if it contains "000". They're attempting to check if it's an empty UUID, and they've assumed that three sequential zeroes in the output would be an impossible event. This is untrue. Nikolai measured it, and found it happens 0.5527% of the time- 1-in-181.

So this is a bad test, and could be made better with a more thorough check. Or it could leverage the built in constant GUID.Empty, which is a UUID where every bit is zero.

And it's that which really bugs me, honestly. Even if you didn't know about the constant, the idea of constructing an empty GUID seems like the obvious choice. Though I suppose you'd have to check the docs to find out how to construct a GUID directly, and if you're already reading the docs, the chances of you seeing the built-in constant are probably higher than 0.5527%.

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.
Remy Porter

It's All Part 2 of the Process

3 weeks 5 days ago

Our submitter Tim C. is back as his bureaucratic nightmare continues. Read Part 1 here.

After I'd thrown the WTF Exchange (WTFX) for a loop, they managed to eventually right the ship. But then I faced another hurdle: I had run out of disk space. The software was not live, we were still developing the customer-specific customisations, but I was a bit stuck without a few more gigabytes.

The exchange went something like this:

"Hey Margritte, I need more disk space."

"Oh dear, what's happening?"

"Nothing is happening. I'm just developing the software. I need more disk space, not much. Can you get me another 20Gb? Wait, make that 40Gb."

"We can't just get you more disk space. These things need to be planned!"

"I just need a tiny amount, really. No need for any meetings. Just tell your IT guys to give me another NFS drive or expand one of the existing ones."

"Tim, that's not how things work here. We need to discuss your needs and it's important to us to know what needs you might have in future."

"Um, okay ... ?"

"I'll try to call an urgent meeting."

"Really? For 40Gb?"

"Well, how do we know 40Gb is going to be enough?"

"Because it's double what I really think I need."

"Why on Earth didn't you tell us before that you needed this disk space?"

"I'm telling you now!"

"Why didn't you do projections months ago?"

"At no stage did anyone ask me how much disk space we need! We obviously need some disk space! I have literally never given anyone an estimate! We are not even at the point yet to even estimate how much we'll need on project go-live."

"Well, I'll try to get an urgent meeting going. But it won't be today."

So at lunchtime, I went to the local computer store and bought an external hard drive. I asked Margritte to give it to the IT guys to stick somewhere in their computer room, or at least somewhere on their network.

That just seemed to make things worse.

"We can't take this! We have procurement processes!"

"Take it! This is a freebie from me to you. It'll help unstick a blockage in the project."

"It's not our standard hardware vendor. God knows what stuff is on it. We can't take the risk."

"I have literally not opened the plastic sealed wrapper on the outside of the box."

"Yes, but you could have re-sealed it. When we go via our trusted hardware partners we don't have to worry about things like that."

"You realise I'm making software every day which is running in the heart of your systems?! I work on this laptop here, and at the hotel, creating software, both C++ source code and Windows executables, that run inside your systems!"

"But it's not in the asset register. We need to record the warranty details every time we install hardware. What happens if it fails after you've left?"

"Well, how about we just agree I'll take it with me when I go?"

"Okay, I'll see if I can make the meeting happen tomorrow. To get you more disk space. Using our preferred hardware. Not that ... thing." (Said with disgust.)

Well, I finally got my disk space ... after a couple of days.

I was shocked to learn months later what a small proportion of the overall project budget our company earned. What seemed like an enormous multi-million-dollar contract to us was dwarfed by what WTFX spent on ex-pat "Anderson Androids", all immaculately groomed with expensive suits, who spent weeks twiddling their thumbs in expensive hotel rooms waiting for us to finish our software development, because they couldn't start until we had finished.

So sayeth the Gantt chart! Amen.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
Ellis Morning
Checked
1 hour 56 minutes ago
Curious Perversions in Information Technology
Subscribe to The Daily WTF feed