25

Possible Duplicates:
What is the worst code you’ve ever written?
What programming hack from your past are you most ashamed of?
Most shameful/awesome language hack

Possible Duplicate:
What is the worst code you’ve ever written?

Duplicate

What's the worst code you've ever written?
Most shameful/awesome language hack

Today my friend sent me a line of code that he just found while attempting to debug and it got me wondering what others have found. So, in your coding travels, what is the line of code that has made you most think to yourself, "Oh...this can't be good.".

To start things off:

const float nearZero = 0.0000001;

Edit 2: To specify: I'm most curious about single lines of code, not entire blocks.

Edit 3: Also, to clarify, I'm not saying the code is necessarily bad upon further inspection. I'm just looking for first glance "Oh no" kind of moments.

79 accepted
Dictionary<int, Dictionary<string, Dictionary<int, Dictionary<int, 
             Dictionary<string, string>>>>> status 
    = new Dictionary<int, Dictionary<string, Dictionary<int, 
            Dictionary<int, Dictionary<string, string>>>>>();
64

OK, it's two lines, but this is still my favourite:

// initialise the static variable to 0
count = 1;
46
'Option Explicit

"Hey! I sorted it! It was this line at the top, comment it out and the error goes away!" :)

42
/* hahahahahahahaha */
41
bool b = (i == 3) ? true : false;
38

Within a piece of code brought in by an interview candidate:

Dim Dave as String

Unsurprisingly he has forever been referred to as 'dim dave'

36
On Error Resume Next
29

Coworker once saw this in code. We still laugh about it.

int fiftyOne = 51;

28
pointer = 1+1-2; // null out the pointer properly.

or how about...

//UpdateSomething(deltaTime);  // TODO: uncomment this after the show.
26
if (boolean_test_here_which_is_usually_true); {
  // stuff
}

Took me a while to figure out why the block was running even in the rare case when the condition was false.

24
using System;

namespace Biz.Your.Company.Goes.Here.Util
{
    public sealed class SuccessException : Exception
    {
     public SuccessException() : base()
     {
      System.Environment.Exit(1);
     }

     public SuccessException(string msg) : base(msg)
     {
      System.Environment.Exit(1);
     }

     public SuccessException(string msg, Exception exception) : base(msg, exception)
     {
      System.Environment.Exit(1);
     }
    }
}
19
void *myPtr = Ox0BADC0DE;
18

From a project I used to work on:

bool flag = Boolean.Parse("True");

and elsewhere in the same code file, by the same person:

if (chkTerm.Checked == Boolean.Parse("False"))
{
    ...
}
15
CommentId1, CommentId2, CommentId3, .... , CommentId78 = 0;
15
Dim isResult as Boolean = doesWork()
If isResult = true then
    If isResult = false then
        ' do Some Work
        ''' don't know how they planned on getting here
    Else
        ' do Some Work
    End If
Else
    'do some work
End If
15
if (someArray.length > 0 && someArray != null) ...

The fact that this pattern appeared all over the code, along with other massive WTFs, convinced me that this was not simply a typo.

14

Comment

// We should remove this terrible hack before we ship

In a file that has not been revised for years

13

How about comments like this?

# test if this value is true, and if it is, print result
if (value is True):
    print result
11

Years ago in comp.lang.c.moderated, a similar contest was held. As I recall, the winner there was:

#define false 1
#define true 0

This, of course, was long before C had true or false built in.

10
if(!tempMessage.equals(null)){...
10

Ternary abuse FTL!

On one application I used, every if statement was written in ternary form:

if (someFlag == true ? true : false)
//from the department of redundancy department

Once the developers discovered ternary chaining, the gods themselves weeped:

char status = user.Type.ToString() == "Admin" ? 'C' :
                  administrativeOverride(txtUsername.Text, txtPassword.Text) ? 'X' :
                      user.IsLoggedIn && (user.NeedsEOD || !user.Accounts[0].OutOfBalance) ? 'P' :
                          user.ID == -1 /* test only! */ ? 'T' : '-';
10

This is one from a small open-source project i worked on from time to time.

The culprit was "hard to work with" (insert whatever mean name you'd like to call that type of person there) so was asked to resign from the project. It was not on particularly bad terms; he was fine with it and simply said OK. He said he would wrap up what he was working on and commit (praise dinosaurs we were versioning source). He made a commit of about 50 files.

After we checked out his commit, everything broke. Unfortunately there was some valuable stuff in his commit too... so we had to check diffs on every file to figure out what the problem was.

#define true false //f**k you guys. Have fun.

We didn't.

9
// there be dragons here
8
if (true)

At least there was no else statement.

8

So I don't have a line of code to post, but I feel that it is along the same line as the question.

DBA: "There's something wrong with your batch processing code concerning the interest calculation of auto loans."

Programmer Team Lead: "I know."

DBA: "Don't you think you should fix it?"

Programmer Team Lead: "No, since they are all wrong, we know they are all wrong, and changing the code would change that. Consistency is better than accuracy."

8
if (a % 1)
{
   // this will never be reached!
   // but there was real code in here
}
8
if (variable == someObject)
{
    variable = someObject; // yeah! equality and assignment operators are overloaded. God save C++
}
8

How is possible that nobody hasn't mentioned yet the infamous:

catch {}
8
tmp6 = (tmp1 + tmp2 * (tmp5 / tmp4)) + tmp3

Actualy every line of this code is the Most horrifying line of code i have ever seen.

mTotalesMSF(6) = mTotalesMSF(6) + tmp6 + tmp4
If tmp1 = 0 Then
    tmpCero = 100
Else
    If tmp3 + tmp5 = 0 Then
        tmpCero = 0
    Else
        tmpCero = ((tmp3 + tmp5) / tmp1) * 100
    End If
End If
tmpAdd = tmpAdd + Format(tmp3 + tmp5 - tmp1, "#,##0") + Chr(9)
tmpAdd = tmpAdd + Format(tmpCero, "#,##0") + "%" + Chr(9)
If tmp2 = 0 Then
    tmpCero = 100
Else
    If tmp4 + tmp6 = 0 Then
        tmpCero = 0
    Else
        tmpCero = ((tmp4 + tmp6) / tmp2) * 100
    End If
End If
tmpAdd = tmpAdd + Format(tmp4 + tmp6 - tmp2, "#,##0") + Chr(9)
tmpAdd = tmpAdd + Format(tmpCero, "#,##0") + "%"
mTotalesMSF(7) = mTotalesMSF(7) + tmp4 + tmp6 - tmp2
If tmp1 + tmp2 + tmp3 + tmp4 + tmp5 + tmp6 <> 0 Then sfConsulta.AddItem
7

I kid you not, this line of code was found in a header file for one of our products when we were doing maintenance a couple of years later:

#define PI 3.141592654  /* What the f**k is that! */

I've had to expurgate the comment, but otherwise that is verbatim ('ve literally just copy-and-pasted it in). No-one would own up to being the programmer who didn't know what pi was...

6
for(;r<c;r++,dst1++,b2++,b3++,mask<<=1)

The surrounding code isn't much better... Yea - right! Easy to understand, eh?

6

We once had a program that crashed a lot, but could not locate the bug. I added code to write trace lines to a debugging output file:

dbg = fopen("prog.dbg", "w");
fprintf(dbg, "Debugging started\n");
...

Of course, this particular Heisenbug disappeared at that point. Apparently enough of the internal static memory had been shifted around by my change that the bug no longer trashed critical memory enough to cause a crash. Removing the tracing code brought the bug back, of course.

I didn't have time to really fix the bug, so I left the fopen() call in the code, but changed it to be silently benign:

dbg = fopen("/dev/null", "w");

And that's what we shipped in production.

5
int GenerateRandomNumber()
{
    return 4; // result of a dice throw, guaranteed to be random
}

(seen here)

5

In a multi-user system, the result of this was used in several subs in VB6 before being committed back to the DB as part of a new row :

SELECT Max(ID) + 1 AS NextID FROM Table1
5
Dictionary<int, string> dictionary = new Dictionary<int, string>();
                        dictionary = sourceDictionary;
5

Java

StringBuffer iCalendarRequest = new StringBuffer(
    "BEGIN:VCALENDAR\n"
        + "PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n"
        + "VERSION:2.0\n" + "METHOD:PUBLISH\n" + "BEGIN:VEVENT\n"
        + "ORGANIZER:MAILTO:test@test.de\n" + "DTSTART:"
        + dateFormatter.format(start)
        + "T"
        + timeFormatter.format(start)
        + "A\n"
        + "DTEND:"
        + dateFormatter.format(ende)
        + "T"
        + timeFormatter.format(ende)
        + "A\n"
        + "TRANSP:OPAQUE\n"
        + "SEQUENCE:0\n"
        + "UID:040000008200E00074C5B7101A82E0080000000000278000000000000000\n"
        + " 000004377FE5C37984842BF9440448399EB02\n"
        + "DTSTAMP:"
        + dateFormatter.format(now)
        + "T"
        + timeFormatter.format(now)
        + "Z\n"
        + "LOCATION:Conference room\n"
        + "PRIORITY:3\n"
        + "CLASS:PUBLIC\n" + "END:VEVENT\n" + "END:VCALENDAR").toString();
5

this one is my personal hate:

  if (bResult = true) then
    lResult := true
  else
    lResult := false;

4
string condition = "true";  //boolean text
4
Vector vRes = vA ^ vB;

vRes = vA x vB (ie cross-product). Nice choice of operator there guys, its so obvious what it is ;)

4

I can't remember the exact piece of code, but, essentially, its purpose was to generate a "guaranteed random value" to be used as a key within a database.

Well, this value was generated by appending a string supplied by the user (hopefully unique, but not necessarily so) and appending it with a timestamp of which the timestamp was to the level of minutes (HH:mm). The entire length of the code was a good thirty lines. I couldn't believe my eyes.

I replaced it with a single statement to generate a UUID.

4

boolean t1 = true;

.. some code change t1 ..

if( t1 == true ) 
else if( t1 == false)
else
4
// KEKEKE IM DRUNK!!

shudder

4

In PERL

if $var =~ /(.*)/ { ...

4

What about these gems from someone reluctant to test against constant 0

if (someInt > default(int))

Or, much more worryingly...

if (someInt < int.MinValue)
4

Never had the pleasure of finding any WTF code, but I've come across some great comments in my time:

(* DiscRate := 0.25;  //Just commented out in case the bitch changes her mind again *)

And one of my personal favorites:

(* This is a simple bubble sort, if you don't understand it why did we hire you... don't change it! *)

Right before I left an employer, we were beginning the "Descriptive Variable Name FOR EVERYTHING" phase, so I left them with this gem in a deply buried routine...

var tempVariableWithADescriptiveNameUsedToIterateThroughASetNumberOfItems : Integer;
4
while (true == true);
4

I did maintenance work on a module littered with the 'comments' like this:

// And now we are going to multiply x by 2
x *= 2;

// About to call function y
y( );

I guess at some point there was a mandatory management decision to use comments in the code.

The methods in the module did not have any documentation, naturally.

3

I don't remember the exact code, but it was iterating through an array breaking when catching IndexError exception!

3

came across this in a couple places in a newly checked in file recently :)

if(true) { ...snip... }

and

if(false) { ...snip.... }

no comments or details.

3
// her comes the magic part
3

My own comment after some fixing Microsoft's fuckups:

// MICROSOFT MADE ME DO IT :(

3

This was just a "proof of concept" that I posted in another question, so it's not in any real code (I hope xD):

#define MAX_8(A, B, C, D, E, F, G, H) ((((A)>(B)?(A):(B))>((C)>(D)?(C):(D))?((A)>(B)?(A):(B)):((C)>(D)?(C):(D)))>(((E)>(F)?(E):(F))>((G)>(H)?(G):(H))?((E)>(F)?(E):(F)):((G)>(H)?(G):(H)))?(((A)>(B)?(A):(B))>((C)>(D)?(C):(D))?((A)>(B)?(A):(B)):((C)>(D)?(C):(D))):(((E)>(F)?(E):(F))>((G)>(H)?(G):(H))?((E)>(F)?(E):(F)):((G)>(H)?(G):(H))))
3
 /* TODO holy zombiejesus this is ugly */

(as only comment in front of of a very obscure function called from everywhere)

3

Here's a good one:

if (symbol == null) { lock (symbol) symbol = value; }
3
//i am only responsible for this code if it works

a Lovely comment!

3

Some of the best code I've seen others write is: command.setPropertyName(command.getPropertyName());

That wasn't exactly it, it was cleaned up a bit, but some others wrote code that set the value of the object from its existing value?

3
<br /><br /><strong style="font-weight: bold">Some Text</strong> more text

...repeated about 100x on the page as paragraphs and list items. ugh.

2

In my own code recently:

if (someCondition)
{

}

Just like that. I thought to my self, oh my god, what did I delete without realizing it? After some research and testing, I realized it was only a left over fragment though.

2

Usually the comments scare the most

Like

// I hope I'll fix this bug some time later
2

Java code, done by an obvious beginner:

String name =  new String("");
String addr =  new String("");
String zip =   new String("");
2

The one that always sets my alarm bells off is

using System.Linq;

2

Found in Microsoft's Profile Manager code - available publicly:

// HACK CENTRAL.  This is a MAJOR hack.  MAPI will always return E_ACCESSDENIED
// when we open a profile section on the service if we are a client.  The workaround
// (HACK) is to call into one of MAPI's internal functions that bypasses
// the security check.  We build a Interface to it and then point to it from our
// offset of 0x48.  USE AT YOUR OWN RISK!  NOT SUPPORTED!

Do i need to mention it didn't work for me?

2

I once saw some PHP code that looked something like this:

$page2URL = strrev(strstr(strrev($URL), "/") . "page2.php";
2

-f>@+?*<.-&'_:$#/%!

See How do you google for -f>@+?*<.-&'_:$#/%!? on SuperUser.

2

In order to speed up development, I've seen developers change the field name in a Java class without updating the field in the database. So, it is not uncommon to have a model like this:

public class User
{
  String username;
  String firstName;
  String lastName;

 ...
}

User
{
   userId,
   type,
   code
}

where userId maps to username (not so bad) firstName maps to type, lastName maps to code

This is another reason I vote for hibernate of iBatis. Hibernate helps you follow conventions, if you really want to screw up, you have to go out of your way.

2

Another database development enhancement I thought of.

In order to speed up development even further, I've seen places using Strings (varchar2) for all database columns.

Even columns that should be ints, they're stored as strings. This makes sorting difficult and require an extra computation if you want it in the numerical order.

2

It was something like that:

If SomeBoolean <> False Then
2

inline javascript calls.

2
while (check.flag==true) {};

And most surprisingly was in a project already in production...

Another thread was updating that check.flag but it was still horrible to see....

2
srand(0xC0EDA55);

Was in a buddy's molecular dynamics code. It certainly isn't horrible but it still made me LOL.

1

http://thedailywtf.com/ for all your poor programming needs!

1

I don't remember exactly what the controls were, but it went along the lines of:
result := ((String1 = '') and (String2 <> '')) or ((String1 <> '') and (String2 = ''));

Shortened it to
result := (String1 = '') xor (String2 <> '');
and suddenly performance improved about 10% from these strings actually being functions.

1

I guess you're asking for the location of the The International Obfuscated C Code Contest :-)

As code, the snippet that gives me a oh-no reaction most often is:

if (stringvalue.equals("")) {
1
public static string GetBytes(string info)

Right out of the "public int GetString()" book.

1

Some code I found (not my code):

do
  j = 0
  if j = 0 then
    ' Do stuff
    ' Some other code here...
    j = 1
  end if
  i = i + 1
loop while i < iCnt
1
//Assembly language code here

move eax,X1

I think they'd know better.

0

This usually wouldn't work but it makes me cringe.

rm -rf /

0

I never saw the code, but I remember a developer (a good developer) coming out of his office saying, "You know, I'm actually rather proud of this kludge."