Picking the Grand Prize winner for the Second Olympiad of Misguided Geeks at The Daily WTF was truly a monumental challenge. The grand prize winner needed to embody the most all-around WTF solution possible. There were a plenty of great (terrible) entries but were looking for that one special entry that hurt our souls and ate our brains. Something that made us exclaim "WTF?!"

In the end, it came down to two submissions. Both are great examples of bad development practices, but in the end one outshone the other as worse than failure. So, before we get to the grand prize, let's take a look at the code which almost won.

Runner Up - The Wrong Tool For Every Job

Anyone who has spent too long working with an Oracle database knows that PL/SQL is the real WTF. The Wrong Tool goes above and beyond in its use of PL/SQL to create a solution that… well, the title is accurate.

For example, how does it generate random data? Sure, you could use Oracle's built in DBMS_RANDOM function, but that'd be way too easy.

  FUNCTION generate_random return integer IS
    n_coin_flip integer;
  BEGIN
    select mod(sum(ascii(extractvalue(column_value,'//text()'))),2)
      into n_coin_flip
      from table(XMLSequence(extract(XMLType('<p><l>'||regexp_replace(trim(to_char(to_date(to_char(sys_extract_utc(systimestamp),'SSFF3'),'J'),'Jsp')),'(.)','\1</l><l>')||'</l></p>'),'/p/l')));
    return n_coin_flip;
  END generate_random;

And how does it keep track of pending requests for randomness? “Well, it’s Oracle, so it must be in a database table, right?”

Of course not. It uses AOL Email.

-- connect
    o_socket:=utl_tcp.open_connection
      (remote_host => 'pop.aol.com'
      ,remote_port => 110
      ,tx_timeout  => 5
      ,charset     => 'US7ASCII'
      );
    v_line:=utl_tcp.get_line(o_socket);
    -- authenticate
    v_line:=pop_cmd('USER omgwtfipc');
    v_line:=pop_cmd('PASS cleartext');
    -- retrieve messages
    v_line:=pop_cmd('LIST');
    -- get message count
    n_msgs:=regexp_replace(v_line,'\D')*1;
    log('POP3 message count '||n_msgs);
    -- consume list
    ---- SNIP

Who doesn’t love clear-text passwords right in the code? There’s a lot more great stuff in the source. For example, despite running on a database server, the only way to interact with this software is that it pulls up a Firefox instance to read generated HTML files.

The only prize for being a Runner Up is a sense of deep satisfaction. You’ve made a terrible thing, and that should be its own reward. The submitter asked to be credited solely as “The Wrong Tool for Every Job”, which is apt.

The Grand Prize Winner - GoodDecisions

Selecting the maximum WTF is more of an art than a science. We were humbled by the effort that went into authoring thousands of lines of code piled high with anti-patterns and terrible naming conventions. We saw solutions that looked at the original problem and took a left turn at Albuquerque. After reading through all the entries, we felt like we had become desensitized as to what bad code truly was.

When we reached Chris W’s entry, it was as if we were collectively struck by lightning. Chris’s entry wasn’t the most complex. It wasn’t the weirdest or prettiest. It was a subtly terrible entry. It gave us chills because it was code that we could imagine existing.

Chris W wrote us a little story about how this code was created.

Mike has come up with a winning idea for a shareware app that will surely allow him to retire early. Together with John, his naively optimistic but well-meaning 13-year nephew who is “good at the computers,” Dan, John’s best friend since kindergarten who has recently learned about the C preprocessor, a copy of Visual Studio 2012 Express, and a complete ignorance of source control, he will take on the world of shareware decision-making applications written in MFC.

To us, this code reeks of the sort of thing that might be produced by a self-proclaimed “rock-star” programmer. It’s over-engineered and too clever for its own good.

#define ENGINE(X, nm, dd) class X : public CDecisionEngine { LPCSTR GetName() { return nm; } LPCSTR GetDescription() { return dd; }
#define DECIDE BOOL GetDecision() { 
#define ENGINEEND }};

ENGINE(CCoinFlipEngine, "Coin Flip", "Simulates a coin flip (50/50).")
	DECIDE if (rand() % 2 == 0) THEN_DECIDE(YES) ELSE_DECIDE(NO);
ENGINEEND

This “simple” macro makes it easy for developers to extend this system with multiple engines, and they can get plenty complicated. In the EngineBox.cpp file:

static BOOL m_fFlip;
ENGINE(CFlipFlopEngine, "Flip Flopper", "John Kerry, is that you?")
	DECIDE
		if (m_fFlip == TRUE)
		{
			m_fFlip = FALSE;
		}
		else if (m_fFlip == FALSE)
		{
			m_fFlip = TRUE;
		}
		else
		{
			// not sure why we're ever getting in here, but true flip floppers 
                        // say 'no' first, so we should be okay
			m_fFlip = FALSE;
		}
		return m_fFlip;
ENGINEEND

For managing these engines, it’s useful to play “golf”.

		// too long to type repeatedly...
#define PSHNGN(EEE); m_lpcdeEngines[++i-1] = new C ## EEE();
		PSHNGN(CoinFlipEngine)
		PSHNGN(YesManEngine)
		PSHNGN(NaysayerEngine)
		PSHNGN(FriendEngine)
		PSHNGN(SpouseEngine)
		PSHNGN(FlipFlopEngine)
#undef PUSHENGINE
		m_dcEngines = 5;

It’s especially nice that he tries to clean up the macro when he’s done with it. Tries.

But it’s not enough to simply make decisions. Where would we be without scope creep? This solution also remembers the decisions that have been made, and reinvents some basic data-structures in the process, in the DecisionHistory.cpp file.

unsigned char CDecisionHistory::GetDecisions(BOOL** lpfaDecicions)
{
	 // Since it's auto the garbage collector will handle deleting this.
	auto lpfDecisions = new BOOL[MAX_DECISION_HISTORY_SIZE + 1];

	if (lpfaDecicions != NULL)
	{
		(*lpfaDecicions) = lpfDecisions;
	}

	int bit = 1;
	for (int i = 0; i < MAX_DECISION_HISTORY_SIZE; i++)
	{
		lpfDecisions[i] = m_llDecision & bit;
		bit = bit + bit;
	}

	return m_ubcDecision;
}

What’s exciting about this, you wonder? It’s not the prettiest way to initialize an array from a constant, but is it a true WTF? Well, look at the “constant” used to define this: #define MAX_DECISION_HISTORY_SIZE sizeof(DECISION_STORAGE_TYPE) * 8

Where does DECISION_STORAGE_TYPE come from? Remember that this is a “shareware” app, and that means there needs to be some way to have a “free” and “professional” edition.

#ifdef PROFESSIONAL_EDITION
#define DECISION_STORAGE_TYPE int
#else
#define DECISION_STORAGE_TYPE short
#endif

This history not only can run out and need to be cleared, but it also is persisted across sessions. The save file method is a wonderful blend of everything wrong.

BOOL CDecisionHistory::Save()
{
	// auto is a lifesaver!
	auto folder = new TCHAR[MAX_PATH + 1];
	memset(folder, 0, MAX_PATH * sizeof TCHAR);

	if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, folder) == S_OK)
	{
		auto folder2 = new TCHAR[MAX_PATH + 1];
		memset(folder2, 0, MAX_PATH * sizeof TCHAR);
		if (PathCombine(folder2, folder, "MyApp") != NULL)
		{
			if (CreateDirectory(folder2, NULL) == FALSE)
			{
				if (GetLastError() == ERROR_ALREADY_EXISTS) 
				{
					// this one is fine!
				}
				else
				{
					// there ARE legitimate use cases for goto
					goto botched;
				}
			}
			if (PathCombine(folder2, folder, "MyApp\\Datum2.txt") != NULL)
			{
				if (HANDLE file = CreateFile(folder2, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL))
				{
					char buffer[200] = "";
					sprintf(buffer, "%d %d", Encript(m_ubcDecision), Encript(m_llDecision));
					if (WriteFile(file, buffer, strlen(buffer) * sizeof(char) + 1, NULL, NULL) == TRUE)
					{
						if (CloseHandle(file) == TRUE)
							{
								return TRUE;
						}
					}
				}
			}
		}
	}
botched:
	return FALSE;
}

And finally, these persisted states have to be protected from hackers.

#define CRYPTOKEY 7
int CDecisionHistory::Encript(int lData)
{
	// you casn't protect all your date form every hackyer, but you might as well slow them down a little
	return lData ^ CRYPTOKEY;
}

int CDecisionHistory::Decript(int lData)
{
	return CRYPTOKEY ^ lData;
}

For giving us a perfect storm of code that scares us, and code that is all too depressingly plausible, The Daily WTF is happy to declare Chris W. the champion of The OMGWTF2 contest. You’ve written the worst and most miserable WTF we saw in this contest. May the gods have mercy upon you.

Thanks to everybody who entered. We had a great time going through your entries. Even if we didn't mention your entry in an article, know that you entertained us all here at TDWTF. We loved each and every line of terrible code that you sent us.

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