AfraLisp Blog

The AutoLisp/Visual Lisp/VBA Resource Website

AfraLisp Blog

Home Newsletter Utter Rubbish Coding Tips AutoCAD Tips Contact Downloads WAUN

How To Write Unmaintainable Code

Originally published at http://mindprod.com/unmain.html. Reprinted by special permission from the author. Further reprints, without the express permission of the author are prohibited. Last updated Thursday, 05-Apr-2001 03:41:36 PDT by Roedy Green ©1997-2001 Canadian Mind Products.

Introduction

Never ascribe to malice, that which can be explained by incompetence.

Napoleon

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 wouldn't be able to maintain the code!

You don't 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.

General Principles

Quidquid latine dictum sit, altum videtur.
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 tube taken from the centre of a roll of toilet paper. 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 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.

Naming

"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 computer. That gives you huge latitude to use them to befuddle the maintenance programmer.
 

  1. New Uses For Names For Baby

    book_cover

    20,001 Names For Baby
    0-380-78047-X
    Carol McD. Wallace

    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.

     

  2. 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 FØRTRAN of using i, j, and k for indexing variables, replacing them with ii, jj and kk, warn them about what the Spanish Inquisition did to heretics.
  3. Creative Missspelling

    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 CodeWright search techniques. It works amazingly well. Add an international flavor by spelling theater and theatre in different situations.
  4. 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.
  5. A.C.R.O.N.Y.M.S.

    Use acronyms to keep the code terse. Real men never define acronyms; they understand them genetically.
  6. 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, and to a print on a laser, and to display on the screen). Under no circumstances, succumb to demands to write a glossary with the special purpose project vocabulary unambiguously defined. Doing so would be unprofessional breach of the structured design principle of information hiding.
  7. Use Plural Forms From Other Languages

    A contributor was the proud author of a VMS script that kept track of the "statii" returned from various "Vaxen". Esperanto, Klingon and Hobbitese qualify as languages for these purposes. For pseudo-Esperanto pluraloj, add oj. You will be doing your part toward world peace.
  8. CapiTaliSaTion

    If you use intercapitalization for function names (capitalize the first letter of each word), randomly capitalize the first letter of a syllable in the middle of a word. For example: ComputeRasterHistoGram().
  9. Recycle Classnames as Member Names

    In C/C++: Make sure to create parameters and local variables that have the same name as member variables of the class whose method they appear in. For extra points, create nested local variables inside {} blocks that have the same name as these local variables. The goal is for careful examination of scope to be the only way to tell which context is actually being used. 
  10. Åccented Letters

    Use accented characters on variable names. E.g.

     

      typedef struct { int i; } ínt;

    where the second int's i is actually iacute. Since these are structures the three int's are not interchangeable, but with an 8-bit aware editor it's nearly impossible to distinguish the slant of the accent mark. Insist the new "ints " are for some specific, but very obscure, situation where a standard int won't suffice. It helps to toss extra stuff into the structure before making that claim! 

  11. Exploit Compiler Name Length Limits

    If the compiler will only distinguish the first, say, 8 characters of names, then always use more characters, but vary the endings e.g. var_unit_update() in one case and var_unit_setup() in another. 
  12. Underscore, a Friend Indeed

    Use _ or __ as an identifier.

     

  13. Mix English and Bahasa Indonesia

    If English is your second language, use English for variable names, functions, messages appearing on-screen, and comments. However randomly intersperse them with words chosen from your native language. If your boss insists you use English tell him you can organize your thoughts better in your own language, or allege racial discrimination and threaten to sue your employers for a vast sum of money. Now that your boss does not understand your code you can use obscuration techniques that you would never get away with otherwise and will foil a future maintenance programmer even if she is also a native speaker or is equipped with a bilingual dictionary. 
  14. Extended ASCII

    Extended ASCII characters are perfectly valid as variable names, including ß, Ð, and ñ characters. They are quite impossible to type without copying/pasting. 
  15. Deutch, Français, Esperanto

    If you cannot find the right English word to convey the meaning of a temporary variable (and you ignore the other suggestions about not giving meaningful names to variables), you may use a foreign language word as the name of the variable. For example, instead of using variable "p" for a "point", you may use "punkt", which is the German word for it. Maintenance coders without your firm grasp of German will enjoy the multicultural experience of deciphering the meaning. It breaks the tedium of an otherwise tiring and thankless job. 
  16. Consider equals As A Variable Name

    Choose variable names that are English versions of operators, to get statements like:
     
      openParen = (slash + asterix) / equals;


  • Bedazzling Variable Names

    Choose all variable names to be words that have no association whatsoever with the actual function of the program but which have strong inherent meaning as words. For example, you could end up with statements like:
     
      marypoppins = (julieAndrews + starship) / mailbox;

    This confuses the reader because they have difficulty disassociating the concepts of the words from the logic they're trying to think about. (Combine this with the above method and it's basically impossible to recover, because search and replace becomes impossible.) 

  • Rename and Reuse

    This trick works especially well in Ada, a language immune to many of the standard obfuscation techniques. The people who originally named all the objects and packages you use were morons. Rather than try to convince them to change, just use renames and subtypes to rename everything to names of your own devising. Make sure to leave a few references to the old names in, as a trap for the unwary. 
  • Reuse Names

    Java lets you create methods that have the same name as the class, but that are not constructors. Exploit this to sow confusion. 
  • 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 Schemtions

    Ignore the conventions in Java for where to use upper case in variable and class names i.e. Classes start with upper case, variables with lower case, constants are all upper case, with internal words capitalised. After all, Sun does (e.g. instanceof vs isInstanceOf, Hashtable). Not to worry, the compiler won't even issue a warning to give you away. If your boss forces you to use the conventions, when there is any doubt about whether an internal word should be capitalised, avoid capitalising or make a random choice, e.g. use both inputFileName and outputfilename. You can of course drive your team members insane by inventing your own insanely complex naming conventions then berate others for not following them. The ultimate technique is to create as many variable names as possible that differ subtlely from each other only in case. 
  • Lower Case l Looks A Lot Like Digit 1

    Use lower case l to indicate long constants. e.g. 10l is more likely to be mistaken for 101 that 10L is. 
  • Reuse of Global Names as Private

    Declare a global array in module A, and a private one of the same name in the header file for module B, so that it appears that it's the global array you are using in module B, but it isn't. Make no reference in the comments to this duplication. 
  • Recycling Revisited

    Use scoping as confusingly as possible by recycling variable names in contradictory ways. For example, suppose you have global variables A and B, and functions foo and bar. If you know that variable A will be regularly passed to foo and B to bar, make sure to define the functions as function foo(B) and function bar(A) so that inside the functions A will always be referred to as B and vice versa. With more functions and globals, you can create vast confusing webs of mutually contradictory uses of the same names. 
  • 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. 
  • m_

    a naming convention from the world of C++ is the use of "m_" in front of members. This is supposed to help you tell them apart from methods, so long as you forget that "method" also starts with the letter "m". 
  • o_apple obj_apple

    Use an "o" or "obj" prefix for each instance of the class to show that you're thinking of the big, polymorphic picture. 
  • 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:

     

    Insist on using "c" for const in C++ and other languages that directly enforce the const-ness of a variable.

    Seek out and use Hungarian warts that have meaning in languages other than your current language. For example insist on the PowerBuilder "l_" and "a_ " {local and argument} scoping prefixes and always use the VB-esque style of having a Hungarian wart for every control type when coding to C++. Try to stay ignorant of the fact that megs of plainly visible MFC source code does not use Hungarian warts for control types.

    Always violate the Hungarian principle that the most commonly used variables should carry the least extra information around with them. Achieve this end through the techniques outlined above and by insisting that each class type have a custom wart prefix. Never allow anyone to remind you that no wart tells you that something is a class. The importance of this rule cannot be overstated: if you fail to adhere to its principles the source code may become flooded with shorter variable names that have a higher vowel/consonant ratio. In the worst case scenario this can lead to a full collapse of obfuscation and the spontaneous reappearance of English Notation in code!

    Flagrantly violate the Hungarian-esque concept that function parameters and other high visibility symbols must be given meaningful names, but that Hungarian type warts all by themselves make excellent temporary variable names.

    Insist on carrying outright orthogonal information in your Hungarian warts. 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!

    Use to your advantage the principle that the human brain can only hold 7 pieces of information concurrently. For example code written to the above standard has the following properties:

  •  

    A single assignment statement carries 14 pieces of type and name information.

    A single function call that passes three parameters and assigns a result carries 29 pieces of type and name information.

    Seek to improve this excellent, but far too concise, standard. Impress management and coworkers by recommending a 5 letter day of the week prefix to help isolate code written on 'Monam' and 'FriPM'.

    It is easy to overwhelm the short term memory with even a moderately complex nesting structure, especially when the maintenance programmer can't see the start and end of each block on screen simultaneously.

     

    1. Hungarian Notation Revisited

      One follow on trick in the Hungarian notation is "change the type of a variable but leave the variable name unchanged". This is almost invariably done in windows apps with the migration from Win16 :- WndProc(HWND hW, WORD wMsg, WORD wParam, LONG lParam) to Win32 WndProc(HWND hW, UINT wMsg, WPARAM wParam, LPARAM lParam) where the w values hint that they are words, but they really refer to longs. The real value of this approach comes clear with the Win64 migration, when the parameters will be 64 bits wide, but the old "w" and "l" prefixes will remain forever. 
    2. 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.

    Camouflage

    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.
     

    1. 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". 

  • How to Hide Forbidden Globals

    Since global variables are "evil", define a structure to hold all the things you'd put in globals. Call it something clever like EverythingYoullEverNeed. Make all functions take a pointer to this structure (call it handle to confuse things more). This gives the impression that you're not using global variables, you're accessing everything through a "handle". Then declare one statically so that all the code is using the same copy anyway. 

  • 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, _xy_z, _xyz, XY_Z, xY_z, and Xy_z.

    Variables that resemble others except for capitalization and underlines have the advantage of confounding those who like remembering names by sound or letter-spelling, rather than by exact representations.

  • Documentation

    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.

    1. Lie in the comments

      You don't have to actively lie, just fail to keep comments as up to date with the code.

       

    2. 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.

       

    3. 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.

       

    4. 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.

       

    5. 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. 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)

      1.2.4.6.3.13 - Display all impacts for activity where selected mitigations can apply (short pseudocode omitted).

      then... (and this is the kicker) when you write the code, for each of these paragraphs you write a corresponding global function named:

       

        Act1_2_4_6_3_13()

      Do not document these functions. After all, that's what the design document is for!

      Since the design doc is auto-numbered, it will be extremely difficult to keep it up to date with changes in the code (because the function names, of course, are static, not auto-numbered.) This isn't a problem for you because you will not try to keep the document up to date. In fact, do everything you can to destroy all traces of the document.

      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.

       

    6. 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. Remember the words of Thumper in the movie Bambi "If you can't say anything nice, don't say anything at all". 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 criticized.

       

    7. Documenting Variables

      Neverput a comment on a variable. 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, not even a temporary!

       

    8. Disparage In the Comments

      Discourage any attempt to use external maintenance contractors by peppering your code with insulting references to other leading software companies, especial anyone who might be contracted to do the work. e.g.:

       

        /* The optimised inner loop.


    This stuff is too clever for the dullard at Software Services Inc., who would
    probably use 50 times as memory & time using the dumb routines in .
    */
    class clever_SSInc

     

      {


    .. .
    }

     

    If possible, put insulting stuff in syntactically significant parts of the code, as well as just the comments so that management will probably break the code if they try to sanitize it before sending it out for maintenance.

     

  • COMMENT AS IF IT WERE CØBØL ON PUNCH CARDS

    Always refuse to accept advances in the development environment arena. Disbelieve rumors that all functions and variables are never more than one click away and always assume that code developed in Visual Studio 6.0 will be maintained by someone using edlin or vi. To this end insist on Draconian commenting rules that bury the source code.

     

  • Monty Python Comments

    On a method called makeSnafucatedinsert only the comment /* make snafucated */. Never define what snafucatedmeans anywhere. Only a fool does not already know, with complete certainty, what snafucated means. For classic examples of this technque, consult the Sun AWT JavaDOC.

  •  

    Program Design

    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

     

    1. 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. The Algol family of languages which include C and Java treat storing data in an array, Hashtable, flat file and database with totally different syntax. In languages like Abundance, and to some extent Smalltalk, the syntax is identical; just the declaration changes. 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.

       

    2. 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.

       

    3. Be polite, Never Assert

      Avoid the assert() mechanism, because it could turn a three-day debug fest into a ten minute one.

       

    4. Avoid Encapsulation

      In the interests of efficiency, avoid encapsulation. Callers of a method need all the external clues they can get to remind them how the method works inside.

       

    5. Clone & Modify

      In the name of efficiency, use cut/paste/clone/modify. This works much faster than using many small reusable modules. This is especially useful in shops that measure your progress by the lines of code you've written.

       

    6. 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.

       

    7. Dummy Interfaces

      Write an empty interface called something like "WrittenByMe", and make all of your classes implement it. Then, write wrapper classes for any of Java's built-in classes that you use. The idea is to make sure that every single object in your program implements this interface. Finally, write all methods so that both their arguments and return types are WrittenByMe. This makes it nearly impossible to figure out what some methods do, and introduces all sorts of entertaining casting requirements. For a further extension, have each team member have his/her own personal interface (e.g., WrittenByJoe); any class worked on by a programmer gets to implement his/her interface. You can then arbitrary refer to objects by any one of a large number of meaningless interfaces!

       

    8. 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 nervous.

       

    9. Wrap, wrap, wrap

      Whenever you have to use methods in code you did not write, insulate your code from that other dirty code by at least one layer of wrapper. After all, the other author might some time in the future recklessly rename every method. Then where would you be? You could of course, if he did such a thing, insulate your code from the changes by writing a wrapper or you could let VAJ handle the global rename. However, this is the perfect excuse to preemptively cut him off at the pass with a wrapper layer of indirection, before he does anything idiotic. One of Java's main faults is that there is no way to solve many simple problems without dummy wrapper methods that do nothing but call another method of the same name, or a closely related name. This means it is possible to write wrappers four-levels deep that do absolutely nothing, and almost no one will notice. To maximise the obscuration, at each level, rename the methods, selecting random synonyms from a thesaurus. This gives the illusion something of note is happening. Further, the renaming helps ensure the lack of consistent project terminology. To ensure no one attempts to prune your levels back to a reasonable number, invoke some of your code at the application level via each of the levels.

       

    10. Wrap Wrap Wrap Some More

      Make sure all API functions are wrapped at least 6-8 times, with function definitions in separate source files.

       

    11. 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.

       

    12. The Kama Sutra

      This technique has the added advantage of driving any users or documenters of the package to distraction as well as the maintenance programmers. Create a dozen overloaded variants of the same method that differ in only the most minute detail. I think it was Oscar Wilde who observed that positions 47 and 115 of the Kama Sutra were the same except in 115 the woman had her fingers crossed. Users of the package then have to carefully peruse the long list of methods to figure out just which variant to use. The technique also balloons the documentation and thus ensures it will more likely be out of date. If the boss asks why you are doing this, explain it is solely for the convenience of the users. Again for the full effect, clone any common logic and sit back and wait for it the copies to gradually get out of sync.

       

    13. Permute and Baffle

      Reverse the parameters on a method called drawRectangle(height, width) to drawRectangle(width, height) without making any change whatsoever to the name of the method. Then a few releases later, reverse it back again. The maintenance programmers can't tell by quickly looking at any call if it has been adjusted yet. Generalisations are left as an exercise for the reader.

       

    14. Theme and Variations

      Instead of using a parameter to a single method, create as many separate methods as you can. For example instead of setAlignment(int alignment) where alignment is an enumerated constant, for left, right, center, create three methods: setLeftAlignment, setRightAlignment, and setCenterAlignment. Of course, for the full effect, you must clone the common logic to make it hard to keep in sync.

       

    15. Cargill's Quandry

      Take advantage of Cargill's quandary (I think this was his): "any design problem can be solved by adding an additional level of indirection, except for too many levels of indirection." Decompose OO programs until it becomes nearly impossible to find a method which actually updates program state. Better yet, arrange all such occurrences to be activated as callbacks from by traversing pointer forests which are known to contain every function pointer used within the entire system. Arrange for the forest traversals to be activated as side-effects from releasing reference counted objects previously created via deep copies which aren't really all that deep.

       

    16. 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.

       

    17. The Magic Of Global Variables

      The use of global variables is so obvious that no one thought to mention it until this point. 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.

       

    18. 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.

       

    19. 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.

       

    20. Local Variables

      Never use local variables. Whenever you feel the temptation to use one, make it into an instance or static variable instead to unselfishly share it with all the other methods of the class. This will save you work later when other methods need similar declarations. C++ programmers can go a step further by making all variables global.

       

    21. 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.

       

    Testing

    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.

    1. 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.

       

    2. 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.

       

    3. 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 recognize 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.

       

    5. 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.

    Choice Of Language

    Philosophy is a battle against the bewitchment of our intelligence by means of language.

    Ludwig Wittgenstein

    Computer languages are gradually evolving to become more fool proof. Using state of the art languages is unmanly. Insist on using the oldest language you can get away with, octal machine language if you can (Like Hans und Frans, I am no girlie man; I am so virile I used to code by plugging gold tipped wires into a plugboard of IBM unit record equipment (punch cards), or by poking holes in paper tape with a hand punch), failing that assembler, failing that FORTRAN or COBOL, failing that C, and BASIC, failing that C++.

    1. FØRTRAN

      Write all your code in FORTRAN. If your boss ask why, you can reply that there are lots of very useful libraries that you can use thus saving time. However the chances of writing maintainable code in FORTRAN are zero, and therefore following the unmaintainable coding guidelines is a lot easier.

       

    2. Avoid Ada

      About 20% of these techniques can't be used in Ada. Refuse to use Ada. If your manager presses you, insist that no-one else uses it, and point out that it doesn't work with your large suite of tools like lint and plummer that work around C's failings.

       

    3. Use ASM

      Convert all common utility functions into asm.

       

    4. Use QBASIC

      Leave all important library functions written in QBASIC, then just write an asm wrapper to handle the large->medium memory model mapping.

       

    5. Inline Assembler

      Sprinkle your code with bits of inline assembler just for fun. Almost no one understands assembler anymore. Even a few lines of it can stop a maintenance programmer cold.

       

    6. MASM call C

      If you have assembler modules which are called from C, try to call C back from the assembler as often as possible, even if it's only for a trivial purpose and make sure you make full use of the goto, bcc and other charming obfuscations of assembler.

    Dealing With Others

    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.

    1. 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.

       

    2. 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."

       

    3. 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 till 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!

       

    4. 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.

       

    5. Book Of The Month Club

      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.

    Tricks In Offbeat Languages

    Programming in Basic causes brain damage.

    Edsger Wybe Dijkstra

    • SQL Aliasing

      Alias table names to one or two letters. Better still alias them to the names of other unrelated existing tables.

       

    • SQL Outer Join

      Mix the various flavours of outer join syntax just to keep everyone on their toes.

       

    • JavaScript Scope

      "Optimise" JavaScript code taking advantage of the fact a function can access all local variables in the scope of the caller.

       

    • Visual Basic Declarations

      Instead of:

       

        dim Count_num as string


    dim Color_var as string
    dim counter as integer

    use:

     

      Dim Count_num$, Color_var$, counter%

     

     

  • Visual Basic Madness

    If reading from a text file, read 15 characters more than you need to then embed the actual text string like so:

     

      ReadChars = .ReadChars (29,0)

  • ReadChar = trim(left(mid(ReadChar,len(ReadChar)-15,len(ReadChar)-5),7))
    If ReadChars = "alongsentancewithoutanyspaces"
    Mid,14,24 = "withoutanys"
    and left,5 = "without"

     

    Miscellaneous Techniques

    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

     

    1. 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.

       

      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?

       

    2. 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.

       

    3. 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.

       

    4. 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.

       

    5. Carry Only One Hammer

      Stick with what you know and travel light; if you only carry a hammer then all problems are nails.

       

    6. 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.

       

    7. 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 resume in your "Other Tools" section.

       

    8. 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.

       

    9. Collect Coding Standards

      Find all the tips you can on writing maintainable code such as these ones the Square Box Suggestions and flagrantly violate them.

       

    10. 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.

       

    11. 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 recognize 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.

       

    12. 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.

       

    13. 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.

       

    14. 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.

    Philosophy

    The people who design languages are the people who write the compilers and system classes. Quite naturally they design to make their work easy and mathematically elegant. However, there are 10,000 maintenance programmers to every compiler writer. The grunt maintenance programmers have absolutely no say in the design of languages. Yet the total amount of code they write dwarfs the code in the compilers.

    An example of the result of this sort of elitist thinking is the JDBC interface. It makes life easy for the JDBC implementor, but a nightmare for the maintenance programmer. It is far clumsier than the FORTRAN interface that came out with SQL three decades ago.

    Maintenance programmers, if somebody ever consulted them, would demand ways to hide the housekeeping details so they could see the forest for the trees. They would demand all sorts of shortcuts so they would not have to type so much and so they could see more of the program at once on the screen. They would complain loudly about the myriad petty time-wasting tasks the compilers demand of them.

    There are some efforts in this direction: NetRexx, Bali, and visual editors (e.g. IBM's Visual Age is a start) that can collapse detail irrelevant to the current purpose.

     

    The Shoemaker Has No Shoes

    Imagine having an accountant as a client who insisted on maintaining his general ledgers using a word processor. You would do you best to persuade him that his data should be structured. He needs validation with cross field checks. You would persuade him he could do so much more with that data when stored in a database, including controlled simultaneous update.

    Imagine taking on a software developer as a client. He insists on maintaining all his data with a text editor. He is not yet even exploiting the word processor's colour, type size or fonts.

    Think of what might happen if we started storing source code as structured data. We could view the same source code in many alternate ways, e.g. as Java, as NextRex, as a decision table, as a flow chart, as a loop structure skeleton (with the detail stripped off), as Java with various levels of detail or comments removed, as Java with highlights on the variables and method invocations of current interest, or as Java with generated comments about argument names and/or types. We could display complex arithmetic expressions in 2D, the way TeX and mathematicians do. You could see code with additional or fewer parentheses, (depending on how comfortable you feel with the precedence rules ). Parenthesis nests could use varying size and colour to help matching by eye. With changes as transparent overlay sets that you can optionally remove or apply, you could watch in real time as other programmers on your team, working in a different country, modified code in classes that you were working on too.

    You could use the full colour abilities of the modern screen to give subliminal clues, e.g. by automatically assigning a portion of the spectrum to each package/class using a pastel shades as the backgrounds to any references to methods or variables of that class. You could bold face the definition of any identifier to make it stand out.

    You could ask what methods/constructors will produce an object of type X? What methods will accept an object of type X as a parameter? What variables are accessible in this point in the code? By clicking on a method invocation or variable reference, you could see its definition, helping sort out which version of a given method will actually be invoked. You could ask to globally visit all references to a given method or variable, and tick them off once each was dealt with. You could do quite a bit of code writing by point and click.

    Some of these ideas would not pan out. But the best way to find out which would be valuable in practice is to try them. Once we had the basic tool, we could experiment with hundreds of similar ideas to make life easier for the maintenance programmer.

     
    The AutoLisp/Visual Lisp/VBA Resource Website

    Copyright © 1999-Perpetuity by AfraLisp

    All rights reserved.
    Information in this document is subject to change without notice.
    Site created and maintained by Kenny Ramage

    The AutoLisp/Visual Lisp/VBA Resource Website