[2008-03-20 downloaded and converted to single HTML. This is edited version of the original and does not contain all of the text]
By Roedy Green
An early version of this article appeared in Java Developers' Journal (volume 2 issue 6). I also spoke on this topic in 1997-11 at the Colorado Summit Conference. It has been gradually growing ever since. I have had quite a few requests for permission to build links here. You are welcome to create links, but please don't repost the essay since the original changes frequently.
If you enjoyed this essay you might like this one on how to write like a newbie. There is a ton of stuff on this site quite unlike anything else on the web. Have a quick look at my home page or my Java Glossary which is a central place to find out everything you ever wanted to know about Java or perhaps my Gay & Black Glossary. If you want a bird's eye view of all the things I'm involved in, see the CMP home page.
You might also enjoy the famous essays Worse Is Better and The Rise of Worse Is Better on doing the right thing.
In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldnt be able to maintain the code!
You dont want to overdo this. Your code should not look hopelessly unmaintainable, just be that way. Otherwise it stands the risk of being rewritten or refactored.
"Quidquid latine dictum sit, altum sonatur. Whatever is said in Latin sounds profound."
To foil the maintenance programmer, you have to understand how he thinks. He has your giant program. He has no time to read it all, much less understand it. He wants to rapidly find the place to make his change, make it and get out and have no unexpected side effects from the change.
He views your code through a toilet paper tube. He can only see a tiny piece of your program at a time. You want to make sure he can never get at the big picture from doing that. You want to make it as hard as possible for him to find the code he is looking for. But even more important, you want to make it as awkward as possible for him to safely ignore anything.
Programmers are lulled into complacency by conventions. By every once in a while, by subtly violating convention, you force him to read every line of your code with a magnifying glass.
You might get the idea that every language feature makes code unmaintainable not so, only if properly misused.
"When I use a word," Humpty Dumpty said, in a rather scornful tone, "it means just what I choose it to mean - neither more nor less." ~ Lewis Carroll - Through the Looking Glass, Chapter 6
Much of the skill in writing unmaintainable code is the art of naming variables and methods. They don't matter at all to the compiler. That gives you huge latitude to use them to befuddle the maintenance programmer.
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.
Single Letter Variable Names
If you call your variables a, b, c, then it will be impossible to search for instances of them using a simple text editor. Further, nobody will be able to guess what they are for. If anyone even hints at breaking the tradition honoured since FORTRAN of using i, j, and k for indexing variables, namely replacing them with ii, jj and kk, warn them about what the Spanish Inquisition did to heretics.
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
Thesaurus Surrogatisation
To break the boredom, use a thesaurus to look up as much alternate vocabulary as possible to refer to the same action, e.g. display, show, present. Vaguely hint there is some subtle difference, where none exists. However, if there are two similar functions that have a crucial difference, always use the same word in describing both functions (e.g. print to mean "write to a file", "put ink on paper" and "display on the screen").
Eschew the Project Glossary
Under no circumstances, succumb to demands to write a glossary with the special purpose project vocabulary unambiguously defined. Wear your adversary down by tantalising, pretending to give information where there is really none. Disguise your vacuous statements sufficiently so the reader will blame himself for failing to understand.
The reader asks himself, if I am trying to compile the com.mindprod.holidays package, is basedir C:\, C:\com, C:\com\mindprod or C:\com\mindprod\holidays ? You see why you should never use concrete examples? They are too clear. If you are forced to use them, complain that they sound childish and unprofessional. Complain that examples make it look as if that is all the product can do. You want people to appreciate fully very possible variation from the get go. You are not trying to inform, but impress! After all, no academic would be caught dead giving an example. People only respect that which is too abstract to grasp easily.
That's a lot to remember. You will do just fine if all you do when writing documentation is maintain the attitude that people who don't already know this jargon are stupid fools who don't deserve to understand.
Reuse Names
Wherever the rules of the language permit, give classes, constructors, methods, member variables, parameters and local variables the same names. For extra points, reuse local variable names inside {} blocks. The goal is to force the maintenance programmer to carefully examine the scope of every instance. In particular, in Java, make ordinary methods masquerade as constructors.
Underscore, a Friend Indeed
Use _var and __var in identifiers.
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.
When To Use i
Never use i for the innermost loop variable. Use anything but. Use i liberally for any other purpose especially for non-int variables. Similarly use n as a loop index.
Conventions Schmentions
Ignore
Sun's coding conventions, after all, Sun does. Fortunately, the compiler won't tattle when you violate them. The goal is to come up with names that differ subtlely only in case. If you are forced to use the capitalisation conventions, you can still subvert wherever the choice is ambigous, e.g. use both inputFilename and inputfileName Invent your own hopelessly complex naming conventions, then berate everyone else for not following them.
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 2Z 5S il17|! oO0 ;:. 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.
Misleading names
Make sure that every method does a little bit more (or less) than its name suggests. As a simple example, a method named isValid(x) should as a side effect convert x to binary and store the result in a database.
Hungarian Notation
Hungarian Notation is the tactical nuclear weapon of source code obfuscation techniques; use it! Due to the sheer volume of source code contaminated by this idiom nothing can kill a maintenance engineer faster than a well planned Hungarian Notation attack. The following tips will help you corrupt the original intent of Hungarian Notation:
[This portion is condenced of the original]
...Consider this real world example: a_crszkvc30LastNameCol. It took a team of maintenance engineers nearly 3 days to figure out that this whopper variable name described a const, reference, function argument that was holding information from a database column of type varchar(30) named LastName which was part of the table's primary key. When properly combined with the principle that "all variables should be public" this technique has the power to render thousands of lines of source code obsolete instantly!
Obscure film references
Use constant names like LancelotsFavouriteColour instead of blue and assign it hex value of 0x0204FB. 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.
Fun With Colours
It goes without saying you should use numeric colour literals rather than named constants. Unfortunately, most skilled maintenance engineers will have learnt by now that hex coded colour values are easy to decode. E.g. 0x0204FB is
Red = 02 Green = 04 Blue = FB |
Which is clearly pretty much entirely blue.
You want is to use the decimal value, 132347. There's no way without the aid of paper or a calculator that any normal person could convert that into the colour 'blue'. For extra bonus points you can produce a decimal colour that looks like it's expressed as hex, for example 808000. A quick glance would guess half red + half green = darkish yellow, but in fact it's not hex, the real colour is 0xc5440 (a dark cyan).
Have fun making up obscure colour names like algae = 0x556b2f instead of darkolivegreen. Very few people know what colour puce and teal are, but would never admit it. Exploit that.
[This portion is condenced of the original]
"The longer it takes for a bug to surface, the harder it is to find." ~ Roedy
Much of the skill in writing unmaintainable code is the art of camouflage, hiding things, or making things appear to be what they are not. Many depend on the fact the compiler is more capable at making fine distinctions than either the human eye or the text editor. Here are some of the best camouflaging techniques.
WRITE "EFFICIENT" CODE
"We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil." ~ Donald Knuth
"More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason – including blind stupidity." ~ W. A. Wulf
The safest way to disguise your obfuscation work then is to make it look as if your motive for it is making the program run faster.
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 careful attention , would you notice that three lines of code are commented out?
Don't Change Names
Instead of globally renaming to bring two sections of code into sync, go your way and continue inventing new variables that do the same thing.
Long Similar Variable Names
Use very long variable names or class names that differ from each other by only one character, or only in upper/lower case. An ideal variable name pair is swimmer and swimner.
Exploit the failure of most fonts to clearly discriminate between ilI1 or oO08 with identifier pairs like parselnt and parseInt or D0Calc and DOCalc. l is an exceptionally fine choice for a variable name since it will, to the casual glance, masquerade as the constant 1. In many fonts rn looks like an m. So how about a variable swirnrner. Create variable names that differ from each other only in case e.g. HashTable and Hashtable.
Similar-Sounding Similar-Looking Variable Names
Although we have one variable named xy_z, there's certainly no reason not to have many other variables with similar names, such as xy_Z, xy__z and xY_z
Red Herrings
Pepper your code with variables that are never used and methods that are never called. This is most easily done by failing to remove code that is no longer used. You can save the code on grounds someday it may need to be revived. You get bonus points if these drone variables and methods have names similar to actual worker ones. The maintenance programmer will inevitably confuse the two. Changes made to drone code will happily compile, but have no effect.
"Any fool can tell the truth, but it requires a man of some sense to know how to lie well." ~ Samuel Butler (1835 - 1902)
"Incorrect documentation is often worse than no documentation." ~ Bertrand Meyer
Since the computer ignores comments and documentation, you can lie outrageously and do everything in your power to befuddle the poor maintenance programmer.
Lie in the comments
You don't have to actively lie, just fail to keep comments as up to date with the code.
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.
Avoid Documenting the "Obvious"
If, for example, you were writing an airline reservation system, make sure there are at least 25 places in the code that need to be modified if you were to add another airline. Never document where they are. People who come after you have no business modifying your code without thoroughly understanding every line of it.
On the Proper Use Of Documentation Templates
Consider function documentation prototypes used to allow automated documentation of the code. These prototypes should be copied from one function (or method or class) to another, but never fill in the fields. If for some reason you are forced to fill in the fields make sure that all parameters are named the same for all functions, and all cautions are the same but of course not related to the current function at all.
On the Proper Use of Design Documents
When implementing a very complicated algorithm, use the classic software engineering principles of doing a sound design before beginning coding. Write an extremely detailed design document that describes each step in a very complicated algorithm. The more detailed this document is, the better.
In fact, the design doc should break the algorithm down into a hierarchy of structured steps, described in a hierarchy of auto-numbered individual paragraphs in the document. Use headings at least 5 deep (1.2.3.4.5). Make sure that when you are done, you have broken the structure down so completely that there are over 500 such auto-numbered paragraphs. For example, one paragraph might be: (this is a real example)
When you write the code, do not document the functions. After all, that's what the design document is for!
Those who come after you should only be able to find one or two contradictory, early drafts of the design document hidden on some dusty shelving in the back room near the dead 286 computers.
Gotchas
Never document gotchas in the code. If you suspect there may be a bug in a class, keep it to yourself. If you have ideas about how the code should be reorganised or rewritten, for heaven's sake, do not write them down.
What if the programmer who wrote that code saw your comments? What if the owner of the company saw them? What if a customer did? You could get yourself fired. An anonymous comment that says "This needs to be fixed!" can do wonders, especially if it's not clear what the comment refers to. Keep it vague, and nobody will feel personally criticised.
Documenting Variables
Never put a comment on a variable declaration. Facts about how the variable is used, its bounds, its legal values, its implied/displayed number of decimal points, its units of measure, its display format, its data entry rules (e.g. total fill, must enter), when its value can be trusted etc. should be gleaned from the procedural code. If your boss forces you to write comments, lard method bodies with them, but never comment a variable declaration, not even a temporary!
Obsolete Code
Be sure to comment out unused code instead of deleting it and relying on version control to bring it back if necessary. In no way document whether the new code was intended to supplement or completely replace the old code, or whether the old code worked at all, what was wrong with it, why it was replaced etc.
Comment it out with a lead /* and trail */ rather than a // on each line. That way it might more easily be mistaken for live code and partially maintained.
"The cardinal rule of writing unmaintainable code is to specify each fact in as many places as possible and in as many ways as possible." ~Roedy
The key to writing maintainable code is to specify each fact about the application in only one place. To change your mind, you need change it in only one place, and you are guaranteed the entire program will still work. Therefore, the key to writing unmaintainable code is to specify a fact over and over, in as many places as possible, in as many variant ways as possible.
Happily, languages like Java go out of their way to make writing this sort of unmaintainable code easy. For example, it is almost impossible to change the type of a widely used variable because all the casts and conversion functions will no longer work, and the types of the associated temporary variables will no longer be appropriate. Further, if the variable is displayed on the screen, all the associated display and data entry code has to be tracked down and manually modified.
Take advantage of Java's ineptitude. Put data you know will grow too large for RAM, for now into an array. That way the maintenance programmer will have a horrendous task converting from array to file access later. Similarly place tiny files in databases so the maintenance programmer can have the fun of converting them to array access when it comes time to performance tune.
Java Casts
Java's casting scheme is a gift from the Gods. You can use it without guilt since the language requires it. Every time you retrieve an object from a Collection you must cast it back to its original type. Thus the type of the variable may be specified in dozens of places.
If the type later changes, all the casts must be changed to match. The compiler may or may not detect if the hapless maintenance programmer fails to catch them all (or changes one too many). In a similar way, all matching casts to (short) need to be changed to (int) if the type of a variable changes from short to int.
Never Validate
Never check input data for any kind of correctness or discrepancies. It will demonstrate that you absolutely trust the company's equipment as well as that you are a perfect team player who trusts all project partners and system operators. Always return reasonable values even when data inputs are questionable or erroneous.
Be polite, Never Assert
Avoid the assert() mechanism, because it could turn a three-day debug fest into a ten minute one.
Clone & Modify
In the name of efficiency, use cut/paste & modify. This works much faster than using many small reusable modules. This is especially useful in shops that measure your progress by the number of lines of code you've written.
Use Static Arrays
If a module in a library needs an array to hold an image, just define a static array. Nobody will ever have an image bigger than 512 x 512, so a fixed-size array is OK. For best precision, make it an array of doubles. Bonus effect for hiding a 2 Meg static array which causes the program to exceed the memory of the client's machine and thrash like crazy even if they never use your routine.
Use Three Dimensional Arrays
Lots of them. Move data between the arrays in convoluted ways, say, filling the columns in arrayB with the rows from arrayA. Doing it with an offset of 1, for no apparent reason, is a nice touch. Makes the maintenance programmer on his toes.
Mix and Match
Use both accessor methods and public variables. That way, you can change an object's variable without the overhead of calling the accessor, but still claim that the class is a "Java Bean". This has the additional advantage of frustrating the maintenence programmer who adds a logging function to try to figure out who is changing the value.
No Secrets!
Declare every method and variable public. After all, somebody, sometime might want to use it. Once a method has been declared public, it can't very well be retracted, now can it?
This makes it very difficult to later change the way anything works under the covers. It also has the delightful side effect of obscuring what a class is for. If the boss asks if you are out of your mind, tell him you are following the classic principles of transparent interfaces.
Static Is Good
Make as many of your variables as possible static. If you don't need more than one instance of the class in this program, no one else ever will either. Again, if other coders in the project complain, tell them about the execution speed improvement you're getting.
Packratting
Keep all of your unused and outdated methods and variables around in your code. After all - if you needed to use it once in 1976, who knows if you will want to use it again sometime? Sure the program's changed since then, but it might just as easily change back, you "don't want to have to reinvent the wheel" (supervisors love talk like that). If you have left the comments on those methods and variables untouched, and sufficiently cryptic, anyone maintaining the code will be too scared to touch them.
And That's Final
Make all of your leaf classes final. After all, you're done with the project - certainly no one else could possibly improve on your work by extending your classes. And it might even be a security flaw - after all, isn't java.lang.String final for just this reason? If other coders in your project complain, tell them about the execution speed improvement you're getting.
The Magic Of Global Variables
Instead of using exceptions to handle error processing, have your error message routine set a global variable. Then make sure that every long-running loop in the system checks this global flag and terminates if an error occurs. Add another global variable to signal when a user presses the 'reset' button. Of course all the major loops in the system also have to check this second flag. Hide a few loops that don't terminate on demand.
Globals, We Can't Stress These Enough!
If God didn't want us to use global variables, he wouldn't have invented them. Rather than disappoint God, use and set as many global variables as possible.
Each function should use and set at least two of them, even if there's no reason to do this. After all, any good maintenance programmer will soon figure out this is an exercise in detective work, and she'll be happy for the exercise that separates real maintenance programmers from the dabblers.
Globals, One More Time, Boys
Global variables save you from having to specify arguments in functions. Take full advantage of this. Elect one or more of these global variables to specify what kinds of processes to do on the others. Maintenance programmers foolishly assume that C functions will not have side effects. Make sure they squirrel results and internal state information away in global variables.
Bloated classes
To ensure your classes are bounded in the most obtuse way possible, make sure you include peripheral, obscure methods and attributes in every class. For example, a class that defines astrophysical orbit geometry really should have a method that computes ocean tide schedules and attributes that comprise a Crane weather model. Not only does this over-define the class, it makes finding these methods in the general system code like looking for a guitar pick in a landfill.
Subclass With Abandon
Object oriented programming is a godsend for writing unmaintainable code. If you have a class with 10 properties (member/method) in it, consider a base class with only one property and subclassing it 9 levels deep so that each descendant adds one property. By the time you get to the last descendant class, you'll have all 10 properties. If possible, put each class declaration in a separate file. This has the added effect of bloating your INCLUDE or USES statements, and forces the maintainer to open that many more files in his or her editor. Make sure you create at least one instance of each subclass.
"Sedulously eschew obfuscatory hyperverbosity and prolixity."
XML
The XML fad has created a bonanza of opportunities for obfuscation. The basic technique is to pick a random hunk of code, then invent an obscure way of representing its logic in XML. Then replace the piece of code with an XML properties file and an XML parser. Make sure the XML representation you choose is so limited that almost anything other than the original logic cannot be expressed in it. Of course you never document the XML language extension or the parser. Nobody questions the simplicity of XML. Using this technique, you should easily be able to balloon 10 lines of simple Java code up to 100 lines of perfectly opaque XML.
Obfuscated C
Follow the obfuscated C contests on the Internet and sit at the lotus feet of the masters.
Find a Forth or APL Guru
In those worlds, the terser your code and the more bizarre the way it works, the more you are revered.
I'll Take a Dozen
Never use one housekeeping variable when you could just as easily use two or three.
Jude the Obscure
Always look for the most obscure way to do common tasks. For example, instead of using arrays to convert an integer to the corresponding string, use code like this:
char *p; switch (n) { case 1: p = "one"; if (0) case 2: p = "two"; if (0) case 3: p = "three"; printf("%s", p); break; } |
Foolish Consistency Is the Hobgoblin of Little Minds
When you need a character constant, use many different formats: ' ', 32, 0x20, 040. Make liberal use of the fact that 10 and 010 are not the same number in C or Java.
Casting
Pass all data as a void * and then typecast to the appropriate structure. Using byte offsets into the data instead of structure casting is fun too.
The Nested Switch
(a switch within a switch) is the most difficult type of nesting for the human mind to unravel.
Exploit Implicit Conversion
Memorize all of the subtle implicit conversion rules in the programming language. Take full advantage of them. Never use a picture variable (in COBOL or PL/I) or a general conversion routine (such as sprintf in C). Be sure to use floating-point variables as indexes into arrays, characters as loop counters, and perform string functions on numbers. After all, all of these operations are well-defined and will only add to the terseness of your source code. Any maintainer who tries to understand them will be very grateful to you because they will have to read and learn the entire chapter on implicit data type conversion; a chapter that they probably had completely overlooked before working on your programs.
int literals
When using ComboBoxes, use a switch statement with integer cases rather than named constants for the possible values.
If you have an array with 100 elements in it, hard code the literal 100 in as many places in the program as possible. Never use a static final named constant for the 100, or refer to it as myArray.length. To make changing this constant even more difficult, use the literal 50 instead of 100/2, or 99 instead of 100-1. You can further disguise the 100 by checking for a == 101 instead of a > 100 or a > 99 instead of a >= 100.
Consider things like page sizes, where the lines consisting of x header, y body, and z footer lines, you can apply the obfuscations independently to each of these and to their partial or total sums.
These time-honoured techniques are especially effective in a program with two unrelated arrays that just accidentally happen to both have 100 elements. If the maintenance programmer has to change the length of one of them, he will have to decipher every use of the literal 100 in the program to determine which array it applies to. He is almost sure to make at least one error, hopefully one that won't show up for years later.
There are even more fiendish variants. To lull the maintenance programmer into a false sense of security, dutifully create the named constant, but very occasionally "accidentally" use the literal 100 value instead of the named constant. Most fiendish of all, in place of the literal 100 or the correct named constant, sporadically use some other unrelated named constant that just accidentally happens to have the value 100, for now. It almost goes without saying that you should avoid any consistent naming scheme that would associate an array name with its size constant.
Semicolons!
Always use semicolons whenever they are syntactically allowed. For example:
if ( a ); else; { int d; d = c; } |
Use Octal For Obscurity
Smuggle octal literals into a list of decimal numbers like this:
array = new int[] { 111, 120, 013, // Sneak it here 121, }; |
Convert Indirectly
Java offers great opportunity for obfuscation whenever you have to convert. As a simple example, if you have to convert a double to a String, go circuitously, via Double with new Double(d).toString() rather than the more direct Double.toString(d). You can, of course, be far more circuitous than that! Avoid any conversion techniques recommended by the Conversion Amanuensis. You get bonus points for every extra temporary object you leave littering the heap after your conversion.
Nesting
Nest as deeply as you can. Good coders can get up to 10 levels of ( ) on a single line and 20 { } in a single method. C++ coders have the additional powerful option of preprocessor nesting totally independent of the nest structure of the underlying code. You earn extra Brownie points whenever the beginning and end of a block appear on separate pages in a printed listing. Wherever possible, convert nested ifs into nested [? : ] ternaries. If they span several lines, so much the better.
C's Eccentric View Of Arrays
C compilers transform myArrayi into *(myArray + i), which is equivalent to *(i + myArray) which is equivalent to imyArray. Experts know to put this to good use. To really disguise things, generate the index with a function:
int myfunc(int q, int p) { return p%q; } myfunc(6291, 8)[Array]; |
Unfortunately, these techniques can only be used in native C classes, not Java.
L o n g L i n e s
Try to pack as much as possible into a single line. This saves the overhead of temporary variables, and makes source files shorter by eliminating new line characters and white space. Tip: remove all white space around operators. Good programmers canx often hit the 255 character line length limit imposed by some editors. The bonus of long lines is that programmers who cannot read 6 point type must scroll to view them.
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.
When To Use Exceptions
Use exceptions for non-exceptional conditions. Routinely terminate loops with an ArrayIndexOutOfBoundsException. Pass return standard results from a method in an exception.
Efficient Exceptions
Throwing an Exception has quite a high overhead. The JVM has to scan the stack looking for a ton of information to potentially use in a stack trace. You can avoid this overhead by constructing a Exception object once and throwing it many times. The stack trace will be for the spot in the code where the Exception was constructed, not where it was thrown. This will really keep them guessing where the bugs are.
Use threads With Abandon
title says it all.
Lawyer Code
Follow the language lawyer discussions in the newsgroups about what various bits of tricky code should do e.g. a=a++; or f(a+,a+); then sprinkle your code liberally with the examples. In C, the effects of pre/post decrement code such as *++b ? (*++b + *(b-1)) : 0 are not defined by the language spec. Every compiler is free to evaluate in a different order. This makes them doubly deadly. Similarly, take advantage of the complex tokenising rules of C and Java by removing all spaces.
Early Returns
Rigidly follow the guidelines about no goto, no early returns, and no labelled breaks especially when you can increase the if/else nesting depth by at least 5 levels.
Avoid {}
Never put in any { } surrounding your if/else blocks unless they are syntactically obligatory. If you have a deeply nested mixture of if/else statements and blocks, especially with misleading indentation, you can trip up even an expert maintenance programmer. For best results with this technique, use Perl. You can pepper the code with additional ifs after the statements, to amazing effect.
Tabs From Hell
Never underestimate how much havoc you can create by indenting with tabs instead of spaces, especially when there is no corporate standard on how much indenting a tab represents. Embed tabs inside string literals, or use a tool to convert spaces to tabs that will do that for you.
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 widget15 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.
// note misleading alignment if ( a ) if ( b ) x=y; else x=z; // the proper alignment is if ( a ) if ( b ) x=y; else x=z; // if the two examples look the same, please notify me. // Sometimes I inadvertently fix the misaligned example // with a bulk tidy. // The top one should look like this: // if ( a ) // if ( b ) x=y; // else x=z; |
The Macro Preprocessor
It offers great opportunities for obfuscation. The key technique is to nest macro expansions several layers deep so that you have to discover all the various parts in many different *.hpp files. Placing executable code into macros then including those macros in every *.cpp file (even those that never use those macros) will maximize the amount of recompilation necessary if ever that code changes.
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 notations: e.g.
byte[] rowvector, colvector, matrix[]; |
which is equivalent to:
byte[] rowvector; byte[] colvector; byte[][] matrix; |
Hide Error Recovery Code
Use nesting to put the error recovery for a function call as far as possible away from the call. This simple example can be elaborated to 10 or 12 levels of nest:
Pseudo C
The real reason for #define was to help programmers who are familiar with another programming language to switch to C. Maybe you will find declarations like #define begin { " or " #define end } useful to write more interesting code.
Confounding Imports
Keep the maintenance programmer guessing about what packages the methods you are using are in. Instead of:
import com.mindprod.mypackage.Read; import com.mindprod.mypackage.Write; |
use:
import com.mindprod.mypackage.*; |
Never fully qualify any method or class no matter how obscure. Let the maintenance programmer guess which of the packages/classes it belongs to. Of course, inconsistency in when you fully qualify and how you do your imports helps most.
Toilet Tubing
Never under any circumstances allow the code from more than one function or procedure to appear on the screen at once. To achieve this with short routines, use the following handy tricks:
Comments at the top of procedures should use templates that are at least 15 lines long and make liberal use of blank lines. Here's a handy template:
/* * Procedure Name: * * Original procedure name: * * Author: * * Date of creation: * * Dates of modification: * * Modification authors: * * Original file name: * * Purpose: * * Intent: * * Designation: * * Classes used: * * Constants: * * Local variables: * * Parameters: * * Date of creation: * * Purpose: */ |
The technique of putting so much redundant information in documentation almost guarantees it will soon go out of date, and will help befuddle maintenance programmers foolish enough to trust it.
Encapsulate The Trivial
Create entire classes or methods to encapsulate trivialities that could never possibly change, but which then require complex invocation, and careful unravelling to discover that the code does almost nothing. Here is a classic example:
class Truth { boolean isTrue ( boolean assertion ) { if ( assertion != false ) { return assertion; } else { return assertion; } } } ... boolean doIt; Truth trutherizer = new Truth(); if ( trutherizer.isTrue(s.equals(t)) ) { doIt = true; } else { doIt = false; } // hint: all the above accomplishes is: doIt = s.equals(t); |
Loops
The humble canonical for loop: for (int i=0; i<n; i++ ) should never be used. Always randomly disguise it, for example by:
It goes without saying you should never use the compact for:each loop. There many ways to rearrange the parts of an Iterator loop over a Collection so every time the maintenance programmer looks at on a simple Iterator, it appears to be something novel.
"Ambiguity is the mother of confusion." ~Roedy
The greatest skill comes in writing unmaintainable code that even you can't figure out a short time after you write it. The key is ambiguity.
Use the fuzziest, vaguest most general terminology you can come up with, especially for variable names. handle is a great example – a handle to what? processData is a great method name. Was there ever a method written that could not be so described? It cleverly hides any clue to what it does behind a cloud of ambiguity.
So, for example, when you mention the size of a display, make sure you make it abundantly unclear whether you mean to include the margins and/or the menu bar in the size. Mix both definitions in the same program using the same term for both.
If your boss insists you use the unambiguous terms payload size for the display without the margins and Applet size for the total display, subvert him by using just the word size, or use the wrong term occasionally.
Make sure, for example, the reader can't tell whether a variable measures height of a display in lines of text or in pixels or some other unit of measure. Further, you want to seduce the reader into a false sense of security that he does understand. For example, use a variable called lines to measure the height of a text display in pixels.
When dealing with HTML text, make sure the reader can't tell from the variable name, or the declaration comments if you are dealing with plain ASCII text, high ASCII characters, embedded entities e.g. & or embedded tags e.g. <td>. Juggling all four sorts of beast without any convention for distinguishing them will make any head spin.
The Java 1.4 Collections are a great place for introducing ambiguity. Every Collection is just a bunch of non-descript Objects. Who can tell without a close look what sort of Object is in each Collection? Never use Java 1.5 generic types because they give away far too many clues. You can make the code even vaguer by using only interface references e.g. Map m and by reusing variables for quite different sorts of Collection.
The thing a maintenance programmer needs most is a bird's eye picture of how it all works, a precis of the responsibilities of the various classes. There are so many ways it could work, you must not give away any hints. Make him sweat. Force him to read the details of every last line of code to put together that big picture.
The maintenance programmer is always looking for a shortcut – something he can safely ignore. Use ambiguity to give him a false sense of security.
"I don't need to test my programs. I have an error-correcting modem." ~ Om I. Baud
Leaving bugs in your programs gives the maintenance programmer who comes along later something interesting to do. A well done bug should leave absolutely no clue as to when it was introduced or where. The laziest way to accomplish this is simply never to test your code.
Never Test
Never test any code that handles the error cases, machine crashes, or OS glitches. Never check return codes from the OS. That code never gets executed anyway and slows down your test times. Besides, how can you possibly test your code to handle disk errors, file read errors, OS crashes, and all those sorts of events? Why, you would have to either an incredibly unreliable computer or a test scaffold that mimicked such a thing. Modern hardware never fails, and who wants to write code just for testing purposes? It isn't any fun. If users complain, just blame the OS or hardware. They'll never know.
Never, Ever Do Any Performance Testing
Hey, if it isn't fast enough, just tell the customer to buy a faster machine. If you did do performance testing, you might find a bottleneck, which might lead to algorithm changes, which might lead to a complete redesign of your product. Who wants that? Besides, performance problems that crop up at the customer site mean a free trip for you to some exotic location. Just keep your shots up-to-date and your passport handy.
Never Write Any Test Cases
Never perform code coverage or path coverage testing. Automated testing is for wimps. Figure out which features account for 90% of the uses of your routines, and allocate 90% of the tests to those paths. After all, this technique probably tests only about 60% of your source code, and you have just saved yourself 40% of the test effort. This can help you make up the schedule on the back-end of the project. You'll be long gone by the time anyone notices that all those nice "marketing features" don't work. The big, famous software companies test code this way; so should you. And if for some reason, you are still around, see the next item. 4.
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.
Ensuring It Only Works In Debug Mode
If you've defined TESTING as 1
#define TESTING 1 |
This gives you the wonderful opportunity to have separate code sections, such as
#if TESTING==1 #endif |
which can contain such indispensable tidbits as
x = rt_val; |
so that if anyone resets TESTING to 0, the program won't work. And with the tiniest bit of imaginative work, it will not only befuddle the logic, but confound the compiler as well.
"Hell is other people." Jean-Paul Sartre – No Exit 1934
There are many hints sprinkled thoroughout the tips above on how to rattle maintenance programmers though frustration, and how to foil your boss's attempts to stop you from writing unmaintainable code, or even how to foment an RWAR that involves everyone on the topic of how code should be formatted in the repository.
Your Boss Knows Best
If your boss thinks that his or her 20 year old FORTRAN experience is an excellent guide to contemporary programming, rigidly follow all his or her recommendations. As a result, the boss will trust you. That may help you in your career. You will learn many new methods to obfuscate program code.
Subvert The Help Desk
One way to help ensure the code is full of bugs is to ensure the maintenance programmers never hear about them. This requires subverting the help desk. Never answer the phone. Use an automated voice that says "thank you for calling the helpline. To reach a real person press "1" or leave a voice mail wait for the tone". Email help requests should be ignored other than to assign them a tracking number. The standard response to any problem is " I think your account is locked out. The person able to authorise reinstatement is not available just now."
Keep Your Mouth Shut
Be never vigilant of the next Y2K. If you ever spot something that could sneak up on a fixed deadline and destroy all life in the western hemisphere then do not openly discuss it until we are under the critical 4 year event window of panic and opportunity. Do not tell friends, coworkers, or other competent people of your discovery.
Under no circumstances attempt to publish anything that might hint at this new and tremendously profitable threat. Do send one normal priority, jargon encrypted, memo to upper management to cover-your-a$$.
If at all possible attach the jargon encrypted information as a rider on an otherwise unrelated plain-text memo pertaining to a more immediately pressing business concern. Rest assured that we all see the threat too. Sleep sound at night knowing that long after you've been forced into early retirement you will be begged to come back at a logarithmically increased hourly rate!
Baffle 'Em With Bullshit
Subtlety is a wonderful thing, although sometimes a sledge-hammer is more subtle than other tools. So, a refinement on misleading comments: create classes with names like FooFactory containing comments with references to the GoF creational patterns (ideally with http links to bogus UML design documents) that have nothing to do with object creation. Play off the maintainer's delusions of competence.
More subtly, create Java classes with protected constructors and methods like
Foo f = Foo.newInstance() |
that return actual new instances, rather than the expected singleton. The opportunities for side-effects are endless.
Book Of The Month Club
"I advocate that 'super programmers' who can juggle vastly more complex balls than average guys can, should be banned, by management, from dragging the average crowd into system complexity zones where the whole team will start to drown." ~ Jan V.
Join a computer book of the month club. Select authors who appear to be too busy writing books to have had any time to actually write any code themselves. Browse the local bookstore for titles with lots of cloud diagrams in them and no coding examples. Skim these books to learn obscure pedantic words you can use to intimidate the whippersnappers that come after you. Your code should impress. If people can't understand your vocabulary, they must assume that you are very intelligent and that your algorithms are very deep. Avoid any sort of homely analogies in your algorithm explanations.
Pose as a Genius
Genius types lead (blindly) without caring much whether the average programmers can fully keep up or not (some even take sadistic pleasure from seeing "ferior" colleagues suffer), and because such team leaders are on an intellectual high, they fail to see that their project is heading for disaster.
You of course can pretend to do the same thing, even if you are not a genius. Tell everyone if they were smart enough, they would have no trouble understanding your unmaintainable code.
Pose as an Idiot
A clever C programmer chafed at the company policy of insisting on the use of named constants instead of using embedded numerical literals. He followed the letter of the law, but avoided its spirit by defining 100 symbolic constants.
#define ONE 1 #define TWO 2 #define THREE 3 ... |
Roll Your Own
You've always wanted to write system level code. Now is your chance. Ignore the standard libraries and write your own. It will look great on your resumé.
Roll Your Own BNF (Bauer Nakkus Form)
Always document your command syntax with your own, unique, undocumented brand of BNF notation. Never explain the syntax by providing a suite of annotated sample valid and invalid commands. That would demonstrate a complete lack of academic rigour. Railway diagrams are almost as gauche. Make sure there is no obvious way of telling a terminal symbol (something you would actually type) from an intermediate one – something that represents a phrase in the syntax.
Never use typeface, colour, caps, or any other visual clues to help the reader distinguish the two. Use the exact same punctuation glyphs in your BNF notation that you use in the command language itself, so the reader can never tell if a (...), [...], {...} or "..." is something you actually type as part of the command, or is intended to give clues about which syntax elements are obligatory, repeatable or optional in your BNF notation. After all, if they are too stupid to figure out your variant of BNF, they have no business using your program.
Roll Your Own Allocator
Everyone knows that debugging your dynamic storage is complicated and time consuming. Instead of making sure each class has no storage leaks, reinvent your own storage allocator. It just mallocs space out of a big arena. Instead of freeing storage, force your users to periodically perform a system reset that clears the heap. There's only a few things the system needs to keep track of across resets – lots easier than plugging all the storage leaks; and so long as the users remember to periodically reset the system, they'll never run out of heap space. Imagine them trying to change this strategy once deployed!
"We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil." ~ Donald Knuth
"If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime." ~ Anonymous
Don't Recompile
Let's start off with probably the most fiendish technique ever devised: Compile the code to an executable. If it works, then just make one or two small little changes in the source code in each module. But don't bother recompiling these. You can do that later when you have more time, and when there's time for debugging. When the hapless maintenance programmer years later makes a change and the code no longer works, she will erroneously assume it must be something she recently changed. You will send her off on a wild goose chase that will keep her busy for weeks.
Foiling Debuggers
A very simple way to confound people trying to understand your code by tracing it with a line debugger, is to make the lines long. In particular, put the then clause on the same line as the if. They can't place breakpoints. They can't tell which branch of an if was taken.
S.I. vs American Measure
In engineering work there are two ways to code. One is to convert all inputs to S.I. (metric) units of measure, then do your calculations then convert back to various civil units of measure for output. The other is to maintain the various mixed measure systems throughout. Always choose the second. It's the American way!
CANI
Constant And Never-ending Improvement. Make "improvements" to your code often, and force users to upgrade often - after all, no one wants to be running an outdated version. Just because they think they're happy with the program as it is, just think how much happier they will be after you've "fixed" it! Don't tell anyone what the differences between versions are unless you are forced to - after all, why tell someone about bugs in the old version they might never have noticed otherwise?
About Box
The About Box should contain only the name of the program, the names of the coders and a copyright notice written in legalese. Ideally it should link to several megs of code that produce an entertaining animated display. However, it should never contain a description of what the program is for, its minor version number, or the date of the most recent code revision, or the website where to get the updates, or the author's email address. This way all the users will soon all be running on different versions, and will attempt to install version N+2 before installing version N+1.
Ch ch ch Changes
The more changes you can make between versions the better, you don't want users to become bored with the same old API or user interface year after year. Finally, if you can make this change without the users noticing, this is better still - it will keep them on their toes, and keep them from becoming complacent.
Put C Prototypes In Individual Files
instead of common headers. This has the dual advantage of requiring a change in parameter data type to be maintained in every file, and avoids any chance that the compiler or linker will detect type mismatches. This will be especially helpful when porting from 32 -> 64 bit platforms.
No Skill Required
You don't need great skill to write unmaintainable code. Just leap in and start coding. Keep in mind that management still measures productivity in lines of code even if you have to delete most of it later.
Carry Only One Hammer
Stick with what you know and travel light; if you only carry a hammer then all problems are nails.
Standards Schmandards
Whenever possible ignore the coding standards currently in use by thousands of developers in your project's target language and environment. For example insist on STL style coding standards when writing an MFC based application.
Bypassing Company Coding Standards
Some companies have a strict policy of no numeric literals; you must use named constants. It is fairly easy to foil the intent of this policy. For example, one clever C++ programmer wrote:
#define K_ONE 1 #define K_TWO 2 #define K_THOUSAND 999 |
Collect Coding Standards
Find all the tips you can on writing maintainable code such as the Square Box Suggestions and flagrantly violate them.
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 no one 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.
Third Party Libraries
Include powerful third party libraries in your project and then don't use them. With practice you can remain completely ignorant of good tools and add the unused tools to your resumé in your "Other Tools" section.
Avoid Libraries
Feign ignorance of libraries that are directly included with your development tool. If coding in Visual C++ ignore the presence of MFC or the STL and code all character strings and arrays by hand; this helps keep your pointer skills sharp and it automatically foils any attempts to extend the code.
Create a Build Order
Make it so elaborate that no maintainer could ever get any of his or her fixes to compile. Keep secret SmartJ which renders make scripts almost obsolete. Similarly, keep secret that the javac compiler is also available as a class. On pain of death, never reveal how easy it is to write and maintain a speedy little custom java program to find the files and do the make that directly invokes the sun.tools.javac.Main compile class.
More Fun With Make
Have the makefile-generated-batch-file copy source files from multiple directories with undocumented overrwrite rules. This permits code branching without the need for any fancy source code control system, and stops your successors ever finding out which version of DoUsefulWork() is the one they should edit.
IDE, Not Me!
Put all the code in the makefile: your successors will be really impressed how you managed to write a makefile which generates a batch file that generates some header files and then builds the app, such that they can never tell what effects a change will have, or be able to migrate to a modern IDE. For maximum effect use an obsolete make tool, such as an early brain dead version of NMAKE without the notion of dependencies.
Compiler Warnings
Be sure to leave in some compiler warnings. Use the handy "-" prefix in make to suppress the failure of the make due to any and all compiler errors. This way, if a maintenance programmer carelessly inserts an error into your source code, the make tool will nonetheless try to rebuild the entire package; it might even succeed! And any programmer who compiles your code by hand will think that they have broken some existing code or header when all that has really happened is that they have stumbled across your harmless warnings. They will again be grateful to you for the enjoyment of the process that they will have to follow to find out that the error was there all along.
Extra bonus points: make sure that your program cannot possibly compile with any of the compiler error checking diagnostics enabled. Sure, the compiler may be able to do subscripts bounds checking, but real programmers don't use this feature, and neither should you. Why let the compiler check for errors when you can use your own lucrative and rewarding time to find these subtle bugs?
Combine Bug Fixes With Upgrades
Never put out a "bug fix only" release. Be sure to combine bug fixes with database format changes, complex user interface changes, and complete rewrites of the administration interfaces. That way, it will be so hard to upgrade that people will get used to the bugs and start calling them features. And the people that really want these "features" to work differently will have an incentive to upgrade to the new versions. This will save you maintenance work in the long run, and get you more revenue from your customers.
Change File Formats With Each Release Of Your Product
Yeah, your customers will demand upwards compatibility, so go ahead and do that. But make sure that there is no backwards compatibility. That will prevent customers from backing out the newer release, and coupled with a sensible bug fix policy (see above), will guarantee that once on a newer release, they will stay there. Extra bonus points: Figure out how to get the old version to not even recognise files created by the newer versions. That way, they not only can't read them, they will deny that they are even created by the same application! Hint: PC word processors provide a useful example of this sophisticated behaviour.
Compensate For Bugs
Don't worry about finding the root cause of bugs in the code. Simply put in compensating code in the higher-level routines. This is a great intellectual exercise, akin to 3D chess, and will keep future code maintainers entertained for hours as they try to figure out whether the problem is in the low-level routines that generate the data or in the high-level routines that change various cases all around. This technique is great for compilers, which are inherently multi-pass programs. You can completely avoid fixing problems in the early passes by simply making the later passes more complicated. With luck, you will never have to speak to the little snot who supposedly maintains the front-end of the compiler. Extra bonus points: make sure the back-end breaks if the front-end ever generates the correct data.
Use Spin Locks
Avoid actual synchronization primitives in favor of a variety of spin locks – repeatedly sleep then test a (non-volatile) global variable until it meets your criterion. Spin locks are much easier to use and more "general" and "flexible " than the system objects.
Sprinkle sync code liberally
Sprinkle some system synchronization primitives in places where they are not needed. I came across one critical section in a section of code where there was no possibility of a second thread. I challenged the original developer and he indicated that it helped document that the code was, well, "critical!"
Graceful Degradation
If your system includes an NT device driver, require the application to malloc I/O buffers and lock them in memory for the duration of any transactions, and free/unlock them after. This will result in an application that crashes NT if prematurely terminated with that buffer locked. But nobody at the client site likely will be able to change the device driver, so they won't have a choice.
Custom Script Language
Incorporate a scripting command language into your client/server apps that is byte compiled at runtime.
Compiler Dependent Code
If you discover a bug in your compiler or interpreter, be sure to make that behaviour essential for your code to work properly. After all you don't use another compiler, and neither should anyone else!
A Real Life Example
Here's a real life example written by a master. Let's look at all the different techniques he packed into this single C function.
void* Realocate(void*buf, int os, int ns) { void*temp; temp = malloc(os); memcpy((void*)temp, (void*)buf, os); free(buf); buf = malloc(ns); memset(buf, 0, ns); memcpy((void*)buf, (void*)temp, ns); return buf; } |
How To Fix Unused Variable Errors
If your compiler issues "unused local variable" warnings, don't get rid of the variable. Instead, just find a clever way to use it. My favorite is:
i = i; |
It's The Size That Counts
It almost goes without saying that the larger a function is, the better it is. And the more jumps and GOTOs the better. That way, any change must be analysed through many scenarios. It snarls the maintenance programmer in the spaghettiness of it all. And if the function is truly gargantuan, it becomes the Godzilla of the maintenance programmers, stomping them mercilessly to the ground before they have an idea of what's happened.
A Picture is a 1000 Words; A Function is 1000 Lines
Make the body of every method as long as possible - hopefully you never write any methods or functions with fewer than a thousand lines of code, deeply nested, of course.
One Missing File
Make sure that one or more critical files is missing. This is best done with includes of includes. For example, in your main module, you have
#include <stdcode.h> |
Stdcode.h is available. But in stdcode.h, there's a reference to
#include "a:\\refcode.h" |
and refcode.h is no where to be found.
Write Everywhere, Read Nowhere
At least one variable should be set everywhere and used almost nowhere. Unfortunately, modern compilers usually stop you from doing the reverse, read everywhere, write nowhere, but you can still do it in C or C++.