All Coded Smorgasbord

Inspired by the Pop-up Potpourri, the examples presented here aren't necessarily "bad" code nor do they imply the miserable failure that we're all used to reading here. The examples are more-or-less fun snippets of code like ones that we've all written at one time or another.

Mysterious Mysteries of Strange Mystery

by in Coded Smorgasbord on

Code is a window into the programmer’s mind. Our thought processes are laid bare, exposed and cemented for all eternity in keywords and symbols. It’s left there, waiting for another programmer to come by and wonder: “What were they thinking?”

That’s exactly what “seebs” was wondering, when he found this PHP code.


Classic WTF: Holiday Smorgasbord

by in Coded Smorgasbord on

Your Christmas present this year is a pile of WTFs from back in 2005. A veritable holiday smorgasbord. This post wouldn't be here if it didn't exist. --Remy

It's been a while since I've done a smorgasbord post, so here goes ...



A Type of Insanity

by in Coded Smorgasbord on

Types are fundamental to most programming languages. Even the loosest, duckiest type system is still a system of some kind. It’s impossible to be a programmer if you don’t at least have a vague understanding of what types are, what they mean, and how you use them.

Well, not impossible.

The Null Type


If You Want To

by in Coded Smorgasbord on

We pick on date handling code a lot here, simply because there are so many ways to mess up date related code (because dates are hard). In a way, it’s almost like we’re cheating. Even smart programmers could mess that up. What about basic conditional logic? How hard could that be to mess up?

Well Jan L. came across this solution to a simple boundary check- if telegramType is between 100 and 199, it is a payment type telegram.


Dating Woes

by in Coded Smorgasbord on

As we all know- especially those of us who just "sprung ahead" this weekend with Daylight Saving Time- dates, times, and time zones are complicated beasts. Handling them programmatically is even harder. Computerphile put together a great video on this topic, which is worth watching to understand why we receive so many Error’d submissions regarding downloads that claim they won’t finish until after the heat death of the universe.

Here are some examples of mind-bending code attempting to wrangle with an already mind-bending topic...


Efficient WTFery

by in Coded Smorgasbord on

Some horrible code is acres of awful, thousands of tortured lines of mess and horror. Some developers can compress their WTFs down into a handful of lines.

For example, Zlatko was working with a Node.js developer who was big on unit tests. Unfortunately, that developer didn’t understand that you couldn’t write a synchronous test for an asynchronous method- the test will always pass.


Classic WTF - The Long Way

by in Coded Smorgasbord on

2014 was a great year for us and hopefully for you too! Happy 2015 everybody! Enjoy this popular WTF from all the way back in May.


Sometimes, a developer just needs to take the long way around. Sure, a line of code like DateTime StartTime = DateTime.Now looks simple and readable, but what happens if you want the StartTime variable to be not exactly now?


Classic WTF - Sweet Mysteries of Life

by in Coded Smorgasbord on

Check out a Classics republish of one of our most read articles from 2014. Enjoy!


When you read a lot of bad code, you start to get a sense of why the code exists. Often, it’s ignorance- of the language, of the functional requirements, of basic logic. Sometimes, it’s management interference, and the slavish adherence to policy over practicality. Other times, it’s just lazy or sloppy work.


A Priestly Epoch, Running off the Tracts

by in Coded Smorgasbord on

Peter came across this helpful little utility function:

public static DateTime EPOCH_UTC()
{
   DateTime epoch = new DateTime(1980, 1, 1, 0, 0, 0);
   return epoch;
}

Everyone Wants Validation

by in Coded Smorgasbord on

Faibbus works with an international team. Some of his fellow developers don’t quite adhere to the same standards. This code was in a module, and the comments and text were originally in Dutch.

if(this.value.length!=0){

   //because the greater/smaller signs are being escaped  

   if(this.value.length==1){alert('The year must have 4 digits.');this.focus();}

   if(this.value.length==2){alert('The year must have 4 digits.');this.focus();}

   if(this.value.length==3){alert('The year must have 4 digits.');this.focus();}

}

The Long Way

by in Coded Smorgasbord on

Sometimes, a developer just needs to take the long way around. Sure, a line of code like DateTime StartTime = DateTime.Now looks simple and readable, but what happens if you want the StartTime variable to be not exactly now?

Craig’s co-worker figured out a better solution:


Sweet Mysteries of Life

by in Coded Smorgasbord on

When you read a lot of bad code, you start to get a sense of why the code exists. Often, it’s ignorance- of the language, of the functional requirements, of basic logic. Sometimes, it’s management interference, and the slavish adherence to policy over practicality. Other times, it’s just lazy or sloppy work.

And sometimes, the mysterious logic that gave birth to a WTF is just that- a mystery.


Code that Works

by in Coded Smorgasbord on

The first step to working with dates is to learn when to use the built in APIs. The second step is to learn how to do basic arithmetic, as Ron shows us.

if (wishDate.Hour < 10)
{
   while (wishDate.Hour < 10)
   {
       wishDate = wishDate.AddHours(1);
   }
}
else if (wishDate.Hour > 16)
{
   while (wishDate.Hour > 16)
   {
       wishDate = wishDate.AddHours(-1);
   }
}

Comments, Errors, and Log Messages...OH MY!

by in Coded Smorgasbord on
Dave wrote, "Found this comment dated from three years ago. I sure hope that vacation ended well."
//TODO: ask terry about this when he comes back from vacation
//row["VERSION"] = (decimal)row["VERSION"] + 1;
row.AcceptChanges();
row.SetAdded();

 


Ternary Over a New Leaf

by in Coded Smorgasbord on

Dimitry likes it when the bad code he finds can be sung aloud. This particular line can be sung to the tune of “Rule Britannia”.

for (var html in data["html"])
   $(data["html"][html][0]).html(data["html"][html][1]);

A Simple Misunderstanding

by in Coded Smorgasbord on

Some terrible code arises out of terrible business rules which no one truly understands. Some terrible code arises from laziness, sloppiness, or the need to just get it done now.

But there’s a special class of awful code that arises for a complete misunderstanding of how the language is supposed to work. That gives us things like the loop Rasmus found:


Comments

by in Coded Smorgasbord on

Comments are a vital part of making code readable, but they’re more than just documentation. They’re communication between one developer and another. They tell us what the code does, but also how we feel about it.

Scott found this, which conveys a most fervent hope for this block of code:


The New TODO and More

by in Coded Smorgasbord on

While wading through hundreds of disallowed implicit casts and such from turning option strict on for a large project, Tevildo came across this little gem.

Sort of like Visual Studio's comment tasks except potentially visible to the user. Who knows, it might actually get attended to if a user reports it as a bug.


Code Comedians

by in Coded Smorgasbord on

When it comes to bad code, everybody thinks they’re a comedian. Heck, look at us! Stupid programmer jokes are a game everyone can play, though, so let’s enjoy an evening at the Improv with some code comedians.

Brian sends us this enum, which I’m sure was very funny back in 2007.


Truth or Sim

by in Coded Smorgasbord on

A huge number of the bad code submitted to TDWTF is related to dates. This isn’t all that surprising- dates are very complex data structures with a vast number of possible representations and huge cultural variations.

I have no idea what the excuse is for all the bad code relating to booleans. Today, let's take a moment to explore some philosophy, and see if we can understand what truth really is.


The Secret Squirrel Club, a Gun, and More

by in Coded Smorgasbord on

"I guess the developer wanted to make make sure that all his bases were covered!" wrote Ryan.

/// <summary>
/// Returns True if the input string is 
/// null, empty, "undefined", or "null".
/// </summary>
/// 

The Object Test, a New PI, and More SHEEIT

by in Coded Smorgasbord on

"I've been trying to fix up the last project a colleague completed before heading for greener pastures," wrote Philip Tyre. "After finding this comment, I'm beginning to have bad thoughts about what I may find lurking around..."

//  Apparently, in at least on situation, a Statically declared public
//  variable will hold its value across different browser instances making calls to the
//  same web page.
//  For now, reset these variables on Page_PreInit.

FAIL FAIL,FAIL FAIL,FAIL FAIL and More

by in Coded Smorgasbord on

"We're had been using a manufacturer's web service, but started getting errors all of a sudden," wrote Peter Lindgren. "Something has really, really failed."

<StatusCode>InternalServerError</StatusCode>
<StatusDescription>Internal Server Error</StatusDescription>
<WebHeaders>
  <X-Backside-Transport>FAIL FAIL,FAIL FAIL,FAIL FAIL</X-Backside-Transport>
</WebHeaders>

EvalToInteger, 'gumdrops', and More

by in Coded Smorgasbord on

"I recently found this while going over some code in a Util library used by my project," Ian writes, "clearly, this method makes sure the job gets done."

public static int EvalToInteger(string statement) {
     string s = EvalToString(statement);
     return int.Parse(s.ToString());
}

Schizophrenic Haiku Comments and More

by in Coded Smorgasbord on

"I found a schizophrenic comment that either intentionally or unintentionally happens to be a haiku," wrote Ben Vanik, "svn blame says this single line is the work of 3 different people across 3 years of coding."

// should delete the temp files here, no cannot because, we havent read it in yet!

Useless Functions, Extreme Naming, and More

by in Coded Smorgasbord on

"We had a programmer in our company whose specialty was to write functions that embodied his own personal traits," Winston Muller, writes "do absolutely nothing and mislead everyone to think that something was done."

/// <summary>
/// Log the user off the system. The method returns true or false for success or failure
/// </summary>
public bool Logoff(string strUser)
{
  return true;
}

SingleQautedString(), RemoveMeFunction(), Human-Friendly Dates, and More

by in Coded Smorgasbord on

"Following the code-as-a-commodity principle," writes Jan, "our management team not only sends large projects overseas, but goes with the lowest bidder."

/**
 * @param str The string which must put into 2 Signle Quat
 * @return The single quated String
 */
public String SingleQautedString(String str) {
  return "'" + str + "'";
}

Not Non-uninvisible, addfunk(), and More

by in Coded Smorgasbord on

"I just inherited a PHP application and discovered this," writes David Green. "I don't know what's worse: the fact that it says add but is performing subtraction, or that I can't find the accompanying addnoise() function."

public function addfunk($one, $two) {
    $val = $one - $two;
    return $val;
}

Important-Function(), IsNumber(), and More()

by in Coded Smorgasbord on

" "I found a function called 'Important-Function' in a colleague's PowerShell script," wrote B. Versteylen, "after expanding the function, I discovered this."

Function Important-Function()
{
#Hehehehehehe ^^
$logTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" #Just so it looks the same as a regular log entry :+
$randomNumber1Method = New-Object  System.Random
$randomNumber1 = $randomNumber1Method.Next(1,100) 
If ($randomNumber1 -EQ 30) 
	{
	$randomNumber2Method = New-Object System.Random
	$randomNumber2 = $randomNumber2Method.Next(1,15) 
	Switch ($randomNumber2) 
	{ 
     1 {Write-Host $logTime "Watching a colleague pick his nose..."}
     2 {Write-Host $logTime "Solving a binary sudoku puzzle..."}
     3 {Write-Host $logTime "Hoping to return anything useful..."}
     4 {Write-Host $logTime "Slapping random people with a trout..."}
     5 {Write-Host $logTime "Surfing porn sites on the internet..."}
     6 {Write-Host $logTime "Pondering the next move..."}
     7 {Write-Host $logTime "Formatting the hard drive..."}
     8 {Write-Host $logTime "Dividing by `$null..."}
     9 {Write-Host $logTime "Getting a cup of coffee..."}
    10 {Write-Host $logTime "Trying to fit a square into a circle..."}
    11 {Write-Host $logTime "Yawning as a cow races by..."}
    12 {Write-Host $logTime "Milking a goat..."}
    13 {Write-Host $logTime "Playing rock-scissors-paper..."}
    14 {Write-Host $logTime "Reading a manual on WMI..."}
    15 {Write-Host $logTime "Thinking about Jessica in Berlin..."}
	}
	}
}

CompareObjectAsIAlertDocumentOrNullIfNotCastable and More

by in Coded Smorgasbord on

"I found this line of code while doing some cleanup," Adam Aldrich writes, "this has to be the worst way to set a boolean variable to false."

bool memberHasFingerprint = bool.Parse(bool.FalseString);

ISelfAware, Very Thorough, Crazy Hashmaps, and More

by in Coded Smorgasbord on

Seeing that I somehow neglected to publish an article yesterday, I figured today would be a great day for a big ole smorgasbord of interesting code. Enjoy!


"I found the following code in our core architecture library," Steven writes, "I could make a smart-ass comment about needing a reference to get a reference, but I think the code speaks for itself."


Convoluted toString, Interesting Comments, and More

by in Coded Smorgasbord on

"Everyone knows that Russians are the best programmers, and the guy we recently hired is no exception," Kip DeMane wrote, "though his English is a little... off. Here are his comments from a recent commit."

r22795 | t-------- | 2010-05-10 16:06:35 -0400  | 1 line

cleaned code, modified function format_for_rtf . no more 
numbered key to access video array elements, renamed all 
camel toe vars, applied consistent coding formating

In A Rush, Properly Handled, and More

by in Coded Smorgasbord on

"This code was left by the Senior Software Consultant," Michael Wheeler writes, "I'm not sure if it's insurance against 'Return' not returning... or a comment that explained why the line of code was left in."

Public Shared Function GetItemFromValue(ByVal ddlControl As DropDownList) As Integer
    Dim i As Integer
    If ddlControl.Items.Count > 0 Then
        For i = 0 To ddlControl.Items.Count - 1
            If ddlControl.Items(i).Selected() Then
                Return i
                Exit For     'leaving this here cause we're in a rush
            End If
        Next
    End If
End Function

Defensive Programming and a Whole Lot More

by in Coded Smorgasbord on

"Some programmers like to program defensively," wrote Sam, "and then there's some of my coworkers. This is found at the top of nearly every function of our C++ classes."

if (!this) return false;

A Smorgasbord of Classics

by in Coded Smorgasbord on

It's a particularly busy week for me: on top of a few looming deadlines, I'll be at Business of Software 2008 in Boston. So, I figured it'd be the perfect opportunity to revisit some classics.

This article is a jumble of jumbles, pulled a handful of Coded Smorgasbord-style posts; this was definitely a fun series I'd like to bring back, so please do send in your "more-or-less fun snippets of code like ones that we've all written at one time or another."



Coded Smorgasbord: Prepare For Return

by in Coded Smorgasbord on

For more fun-but-not-necessarily-bad code, check out the previous episode: Coded Smorgasboard: Muhahahahaha


It's not that Thorsten doesn't have a sense of humor, it's just that finding this function (which simply processes a list of names and converts them to proper case) after hours of debugging several similarly named functions, it gets a little tiring ...


Coded Smorgasbord: The Pilot Episode

by in Coded Smorgasbord on

It's time for a new series: The Coded Smorgasbord. Inspired by the Pop-up Potpourri, the examples presented here aren't necessarily "bad" code nor do they imply the miserable failure that we're all used to reading here. Like previous "bunch o' code" articles, the examples are more-or-less fun snippets of code like ones that we've all written at one time or another. Enjoy!


Let's start things off with Miki Watts, who came across this line in some API examples provided by an ERP software vendor. J., we're all behind you on this: we hope it's not a bug, too ...


A Collection Of Comments

by in Coded Smorgasbord on

It's time once again to give all those cool-but-too-small-to-make-a-full-post submissions a home ...


Nick was disappointed that, despite all of GetGlobalTime()'s robustness, it didn't actually provide a method to apply the path integral transformation ...