560 blogs tracked7,114 posts indexed

#codesod

31 posts · 1 company · newest first

1

CodeSOD: ReferenceError: HELL is not defined (opens on the source site)

David came across some Java code. This particular block needed to, based on an integer masquerading as an enumerated type, return an amount of time to sleep. It has strong opinions about what should happen when you send it an invalid value: private static int getTime(int mode) { return switch (mode) { case 0 -> 30 * SECOND; case 1 -> 15 * SECOND; case 2 -> 10 * SECOND; case 3 -> 20 * SECOND; case 4 -> 17 * SECOND; case 5 -> 32 * SECOND; default -> // go to hell 1000000000; }; } Now, actually using an enum wouldn't solve this, though it'd make the code more clear. There's always the risk that…

codesodexcerpt only · body stays at the source
From the web
2

CodeSOD: A Living Fossil (opens on the source site)

Today's anonymous submission is a blast from the past. This comes from an intranet HTML page that has been receiving continuous updates for some time. How long? Well, let's take a peek at how it does its layout. b>Extension:b> x5555br /> b>Email:b>: a href="mailto:[email protected]">a>br />br /> td> td width=140> td> tr> tr>td> td>tr> tr>td> td>tr> td> table> center> tr>td>br />td>tr> td> tr> table> br /> br /> td> tr> table> center> td> tr> tr>td width=987 height=4 background="../images/table_bottom_sidebar.jpg">td>tr> table> This is like a coelecanth, or a horeshoe crab. A living fossil.…

codesodexcerpt only · body stays at the source
From the web
3

CodeSOD: Building a Line (opens on the source site)

There's an unofficial category of posts here that I call "Somebody told us string builders were more efficient, so we always use string builders, regardless of whether or not that actually makes sense," or STUSBWMESWAUSBROWONTAMS, for short. Probably should workshop that name some. In any case, Adam sends us a new entry for that collection: Public Function ReadFromFile(ByVal filename As String) As String Dim sb As StringBuilder = New StringBuilder() Dim str As String = String.Empty Using sr As StreamReader = File.OpenText(filename) str = sr.ReadToEnd() sb.Append(str & Constants.vbLf) End…

codesodexcerpt only · body stays at the source
From the web
4

CodeSOD: Next Month (opens on the source site)

One of Sean's colleagues left Initech on good terms. It caused no small amount of surprise that the very next day their billing system started failing. The billing system which the colleauge had worked on. No one truly suspected foul play, it was just a weird coincidence. Still, billing blowing up was a 5 alarm fire, so everyone was throwing every idea out about what could be the cause. Late in the evening, after staring at the code for many hours, Sean found this: if item.next_bill_date.month >= end_date.month item.next_bill_date = nil item.save else ... end If the month of the next billing…

codesodexcerpt only · body stays at the source
From the web
5

CodeSOD: Plenty of IDs (opens on the source site)

Venkat joined a new team in the middle of a big refactoring effort. The code was quite a mess, glued together by long Python scripts with main functions longer than a Tolstoy novel. It was this effort to clean up the code into neat modules that highlighted some logical issues with their implementation. def generate_random_number(): """ Generate a 5 digit random number. """ return "".join(map(str, random.sample(range(0,10),5))) The script this function comes from is a launcher script that provisions a VM to execute code. The VM needs a unique identifier, and we get that random number this way.…

codesodexcerpt only · body stays at the source
From the web
6

CodeSOD: Eventually (opens on the source site)

We were just discussing TODO comments recently, and that motivated Bernard to send us this representative comment.. // TODO: This method should ideally be in tax frame work but due to // the time constraint I am duplicating the code here. // Needs to be refactored. Oct 28, 03. This comment exists in this codebase, unchanged. It has been there for twenty three years. The refactoring has never happened. This comment has seen the world change over the last 23 years, as the technology landscape has shifted and changed, grown and contracted. But this comment, this comment is a constant.…

codesodexcerpt only · body stays at the source
From the web
7

CodeSOD: Only Create Me if I Exist (opens on the source site)

Foreign keys are an important part of making sure the entities in our relational database can be connected back together and queried correctly. It's part of proper data normalization. This isn't shocking, of course: the order line table has a foreign key over to the products table, so that every line item points to a product we sell. That's database 101. Database 201, you'd also think about the times where you have a hierarchy of records, where say, every Employee has a ManagerId, which is a foreign key back to the Employee table itself (and in database 301, you'll understand why having a…

codesodexcerpt only · body stays at the source
From the web
8

CodeSOD: Death of the Auth-Er (opens on the source site)

When writing Perl, it's not unusual to want to die. The die function ends your Perl program with an error string, and you'll often see code like: die "My error" unless $i > 5 or die "Other error" if check(), because Perl just loves the backwards conditionals. What's even more fun with die is how it behaves with eval blocks, so it doesn't always kill your program, sometimes it is how you pass error strings back out of sections of your program. And poor Bobby has inherited some Perl that just really loves to die. public function store() { echo 'Hello'; die; if…

codesodexcerpt only · body stays at the source
From the web
9

CodeSOD: Get It Now (opens on the source site)

"TODO" comments are an inescapable part of our work. Yes, yes, you should just do it right the first time, everything should probably have a ticket in whatever your ticket system is for visibility, but at some point, you're just going to leave a "TODO" behind. But hopefully, the TODO gets TODONE, which is not what happened in Sam C's codebase. function getnow() { //TODO return '2012'; } It's the XKCD, but for years. Or WHAT YEAR IS IN memes. At least it's a relatively recent year, not some far off point from over a decade ago. Wait. 2012 was how long ago? That can't be right. It was just a…

codesodexcerpt only · body stays at the source
From the web
10

CodeSOD: Oh, K? (opens on the source site)

Pierre found this cry for help: for (j = 0; j /* * A poor way to work around some sort of memory * violation. k gets clobbered, so I buffer l with it. * Help? */ for (k = 0, l = 0; k /* c_id */ FPRINTF(output, "%d", l + 1); METAPRINTF((output, "%c", delimiter)); Honestly, I'm always a little worried in C-like languages when the loop variable isn't scoped to the loop and declared in place. Always concerning, so when there's concerns with clobbering, I'm not surprised. This iterates across a set of "districts", and then iterates across a list of customers. Standard output functions are replaced…

codesodexcerpt only · body stays at the source
From the web
11

CodeSOD: Session Recording (opens on the source site)

We still get a fair bit of old school ASP .Net webforms code, which was cutting edge about twenty years ago, but remains a collection of bad choices that tried to make web programming feel like desktop programming. As an aside, what a reversed world we live in today, where everyone uses Electron and our desktop programming feels like web programming. In any case, Thomas sends us some pretty ugly webforms code. Me.Session("Albumid") = CType(e.Item.FindControl("lblAlbumID"), Label).Text If Not Me.Session("Albumid") Is Nothing And Not Me.Session("Uid") Is Nothing Then Me.strDelSQL = "Delete from…

codesodexcerpt only · body stays at the source
From the web
12

CodeSOD: Doing the Assignment (opens on the source site)

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…

codesodexcerpt only · body stays at the source
From the web
13

CodeSOD: A Type of Type Safety (opens on the source site)

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…

codesodexcerpt only · body stays at the source
From the web
14

CodeSOD: A Tool for You (opens on the source site)

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…

codesodexcerpt only · body stays at the source
From the web
15

CodeSOD: A Random Article (opens on the source site)

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…

codesodexcerpt only · body stays at the source
From the web
16

CodeSOD: The Date and Time and Time (opens on the source site)

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…

codesodexcerpt only · body stays at the source
From the web
17

CodeSOD: Very Valid Tokens (opens on the source site)

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. [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.

codesodexcerpt only · body stays at the source
From the web
18

CodeSOD: Quite a Distance from the Right Solution (opens on the source site)

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 1; x++) { for (int y = -radius; y 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…

codesodexcerpt only · body stays at the source
From the web
19

CodeSOD: Historical Pads (opens on the source site)

Tim inherited a fairly antique Visual Basic application some time back. Yes, Visual Basic, not VB .Net. The application is old enough that we might consider it "vintage" or "historical"; it certainly dates from before the millennium. But it has its own unique approach to handling historical dates: mnYear% = CInt(Year(vntDate)) If mnYear% 1000 Then msYear$ = "0" & Trim$(CStr(mnYear%)) Else msYear$ = Trim$(CStr(mnYear%)) End If Insert obligatory complaints about Hungarian notation. What even is vnt. Now, one important thing about this program: it didn't have to handle dates back into the middle…

codesodexcerpt only · body stays at the source
From the web
20

CodeSOD: The John Cage Variable (opens on the source site)

David C sends us a true confession. For my job, I write C++ code as if it was a scripting language (long story) to produce programmatic animations for videos. Given that these are "write-and-run-once-and-never-look-at-it-again" programs, I tend to not try as hard to make my code good. But once I wrote this line of code, I had to take a step back and reevaluate my life choices. fade_out(scene, length4->range(0, 3), length4_3_3, length4[4], length4[5]->range(0, 3)); This is a natural consequence of passing parameters as arrays, it seems; instead of having meaningful named values in a struct or…

codesodexcerpt only · body stays at the source
From the web
21

CodeSOD: Vintage 2013 (opens on the source site)

Today we have more of a representative comment, from Watson. This comes from some GPL licensed code published by everybody's favorite evil empire, Oracle. /* * Copyright (c) 2011, 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013…

codesodexcerpt only · body stays at the source
From the web
22

CodeSOD: Extremely One Line (opens on the source site)

Autoformatting your code is a standard thing to do these days. And in those days past, if we're being honest. There's no excuse to not use some kind of autoformatter. Whether you configure your editor to do it or are a weirdo like me who runs a formatter from the CLI as a build step, you've got an easy way to format your code so it looks neat and readable. And some IDEs, like Visual Studio, are pretty insistent about doing this for you. Which makes today's code sample a bit more perplexing. This comes from an ancient ASP .Net application that Austin has the misfortune to work with: protected…

codesodexcerpt only · body stays at the source
From the web
23

CodeSOD: An Odd Sort (opens on the source site)

Let's say we wanted to query Active Directory and print out a report of all of our users, and their last logon time. That seems like a pretty normal task for a Powershell script. It'd probably be short and easy to read, at least if it were written by a normal person. Alice sends us one that wasn't. She's already done us a favor, as she writes: "Code cleaned up and indented for the whitespace-missing-impaired." ##################################### # lists accounts and selected attributes alphabetically ##################################### foreach( $letter in "a", "b", "c"......"z") {…

codesodexcerpt only · body stays at the source
From the web
24

CodeSOD: I Exist (opens on the source site)

In addition to using an ancient development environment, with terrible UX, Greta also has the misfortune of working in Pascal. Recently, she was diagnosing a bug. The program was reporting that files didn't exist when they definitely existed. She traced the problem down into the system library. Let's see if you can spot what's wrong: { Delphi / Kylix Cross-Platform Runtime Library } { System Utilities Unit } { } { Copyright (c) 1995-2001 Borland Softwrare Corporation } ... function FileAge(const FileName: string): Integer; {$IFDEF MSWINDOWS} var Handle: THandle; FindData: TWin32FindData;…

codesodexcerpt only · body stays at the source
From the web
25

CodeSOD: Asynchronous Directories (opens on the source site)

Eri has a mix of a "true confession" and a "wait, really?" today. The programming language Vala bills itself as a C# like language that compiles into something pretty close to C performance, designed specifically for writing code against Gnome and its associated libraries. One of the C#-isms in brings in is async/await type semantics. You can yield someAsyncFunction(), which returns control to the caller, allowing it to proceed until the yielded function returns an actual value. Because it has asynchronous functions, many library functions for handling I/O are already async. So you can…

codesodexcerpt only · body stays at the source
From the web
26

CodeSOD: Heating Up (opens on the source site)

A common option for retrofitting heating and cooling into older homes is a mini-split, frequently tied to a heat pump. They're (relatively) cheap to install, energy efficient, and can be added without substantial modifications to the home. They also, annoyingly, are mostly controlled via IR remotes, making them challenging to wire up to home automation or even a household thermostat. People have made solutions, and today's code comes from one of those solutions. Which, I want to stress, this code comes from an open source project for home automation, so it's not the code that's wrong, here.…

codesodexcerpt only · body stays at the source
From the web
27

CodeSOD: The Big Family (opens on the source site)

Some time ago, Charles shared with us some awful PHP, aka the most common sort. Today's code sample is maybe a little too big to sum up, but I'll let Charles take a crack at it. It's so bad that even analyzing and laughing at it feels impossible. But it’s so bad, I couldn’t not share it. I’m the only one handling all the IT-related tasks at my company, and I don’t have anyone here to vent or laugh about this kind of thing with. So, I figured, why not share it here? I’m hoping it’ll provide at least a little bit of catharsis or some dark humor. To make sure the confidentiality of the codebase…

codesodexcerpt only · body stays at the source
From the web
28

CodeSOD: Lock 'Em Dead (opens on the source site)

Kevin sends us an exception handler from C++. Let's see if we can spot what's going wrong: catch (Exception::Deadlock) { retry; } When we catch a deadlock happening, we retry. That's not a keyword in C++, and looking at how it's used, it has to be some kind of macro, and I suspect that the macro is hiding a goto underneath it. The real problem, though, is that we suspect we're in a deadlock situation. That means this thread is waiting on a resource held by another thread which is waiting for a resource held by this thread. Neither train may continue until the other has passed. So this retry…

codesodexcerpt only · body stays at the source
From the web
29

CodeSOD: Back to the Lab (opens on the source site)

Matlab is special. Scientists and researchers love it. Programmers hate it, and not just because it uses 1-based arrays. I've worked on a number of projects where the task was "take this Matlab code and convert it to C so we can run it on an embedded CPU". Somehow, in that process, I've avoided learning much about Matlab. Andre works on a team that uses Matlab to manage experimental scenarios. They wanted to do a simple task: generate a set of participant-specific images, store them in a database, and reference them later. Somewhere in the intersection of the database product they were using,…

codesodexcerpt only · body stays at the source
From the web
30

CodeSOD: Never Eating the Cookie (opens on the source site)

Maciej works as a freelancer, and that frequently means picking up old PHP code that nobody wants to support. One project had been lingering for ages with key features missing. Specifically, it was supposed to make HTTP requests to other services on an interval, and use that to populate its data. "The old dev tried, but never got it working." It was Maciej's turn to give it a shot. $ch = curl_init( $url ); curl_setopt( $ch, CURLOPT_COOKIEFILE, $cookie ); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_COOKIE, $cookie); // ... many other options set, of course not in…

codesodexcerpt only · body stays at the source
From the web
31

CodeSOD: Public Private Partnership (opens on the source site)

Eric O was trawling through an API for handling concurrency, and found this little mismatch between the comment and the definition: /// /// private Status, because while this object needs to be able to set the status, consumers should only be able to check it, lest everything break. /// public StatusType Status { get { return _status; } set { if (value != _status) { RaisePropertyChanged("Status"); } } } It's very important we make this property private, lest clients abuse it, and unleash dragons, chaos, and other potential horrors. Given that this happens inside of a concurrency API, I can…

codesodexcerpt only · body stays at the source
From the web
31 shown

Privacy choices

Reading never requires analytics. These choices last 90 days on this browser.

Essential sign-in and security storage always stays on. Read the privacy notice.