Debuggers are for Losers
Join the DZone community and get the full member experience.Join For Free
code defects are not planned ; they are accidents that result from an inability to understand execution flow under different input conditions.
but just as airbags are the last line of defense in a car, a debugger should be the last line of defense for a programmer. defensive driving reduces or eliminates reliance on airbags. defensive driving is proactive, it is using all available data to predict and avoid problems.
the alternative to defensive driving is to drive inattentively and treat driving like you are in a demolition derby.
situations exist where hardware and software debuggers are essential and have no substitutes. but most of the time the debugger is not the best tool to find and remove defects.
debuggers will not fix the defect for you
buggers are not like
where you can throw in your code and some soap, go get some coffee and watch tv, and then 30 minutes later the
defect is removed
you can only fix a defect when you understand the root cause of the problem
remember, removing a defect does not advance your project; your project will be on hold until you resolve the problem. you are better served by making sure the defect never gets into your code rather than learning to become efficient at getting rid of them.
inspiration, not perspiration
a defect is an observation of program behavior that deviates from a specific requirement (no requirements = no defect :-) ). a developer familiar with the codepathways can find defects by simply reasoning about how the observation could arise.
at mcgill , my year was the last one that had to take mainframe programming. debuggers did not existon the mainframe, you would simply submit your code for execution in the batch system, get a code dump if there was a defect, and send the listing and the dumpto the printer.
the nature of mainframes in university was that you would queue up at the high speed printer with the 10—15 other people all waiting for their print-outs.
not having anything else to do, i would think about how my program could have failed – and in the vast majority of cases i was ableto figure out the source of the defect before my listing would print.
the lesson learned was that the ability to think is critical to finding defects.
there is no substitute for the ability to reason through a defect; however, you will accelerate the process of finding defects if you lay down code pathways as simply as possible. in addition, if thereare convoluted sections of code you will benefit by rewriting them, especially if they were written by someone else.
not there when you want them
even if you think the debugger is the best invention since sliced bread most of us can't use a debugger on a customer's production environments .
there are so many production environments that are closed off behind firewalls on computers with minimal o/s infrastructure. mostcustomers are not going to let you mess around with their production environments and it would take an act of god to get the debuggersymbolic information on those computers.
in those environments the typical solution is to use a good logging system (i.e. log4j, etc). the placement of the logging calls will beat the same locations that you would throw exceptions – but since this is adiscussion of debuggers and not debugging we will discuss logging at another time.
debuggers and phantom problems
i worked for one client where enabling the compiler for debugging information actually caused intermittent errors to pop up. the program would crash randomly for no apparent reason and we were all baffled as to the source of the problem. interestingly enough, the problem was only happening in our development environment and not in the production environment.
our performance in development was quite slow and i suspected that our code files with symbolic information were potentially the source of the problem. i started compiling the program without the symbolic information to see if we could get a performance boost.
to my surprise , not only did we get a performance boost but the random crashes vanished. with further investigation we discovered that the symbolic information for the debugger was taking up so much ram that it was causing memory overflows .
debuggers and productivity
has show that the most productive developers are at
least 10x faster
than everyone else.
if you work with a hyper-productive individual then ask them how much time they spend in the debugger, odds are they don't...
do you know who
charles proteus steinmetz
was? he was a pioneer in electrical engineering and retired from ge in 1902. after retirement, ge called him because one of the very complex systems that he had built was broken and ge’s best technicians could not fix it.
charlie came back as a consultant; he walked around the system for a few minutes then took out some chalk and made an x on a part (he correctly identified the malfunctioning part).
charlie then submitted a $10,000 bill to ge, who was taken aback by the size of the bill (about $300,000 today). ge asked for an itemized invoice for the consultation and charles sent back the following invoice:
|making the chalk mark $1|
|knowing where to place it $9999|
debuggers are distracting
as brian w. kernighan and rob pike put it in their excellentbook “ the practice of programming ”
as personal choice, we tend not to use debuggers beyond getting a stack trace or the value of a variable or two. one reason is that it is easy to get lost in details of complicated data structures and control flow; we find stepping through a program less productive than thinking harder and adding output statements and self-checking code at critical places. clicking over statements takes longer than scanning the output of judiciously-placed displays. it takes less time to decide where to put print statements than to single-step to the critical section of code, even assuming we know where that is. more important, debugging statements stay with the program; debugging sessions are transient.
despite a modern debugger’s ability to show an impressive amount of context at the point of execution, it is just a snap shot of avery small portion of the code. it is like trying to get an image of a painting where you can only see a small window at a time. above we show 6snapshots of a picture over time and it is hard to see the big picture.
the above snap shots are small windows on the mona lisa, but it is hard to see the bigger picture from small snap shots. to debug a problem efficiently you need to have a higher level view of the pictureto assess what is going on (effectiveness).
if you have to find defects in code that you have not written then you will still be better off analyzing the overallstructure of the code (modules, objects, etc) than simply single-stepping through code in a debugger hoping to get lucky .
defects occur when we have not accounted for all the behavioral pathways that will be taken through the code relative to all the possible data combinations of the variables.
some common defects categories include:
- uninitialized data or missing resources (i.e. file not found)
- improper design of code pathways
- calculation errors
- improper persistent data adjustment (i.e. missing data)
the same way that we have defensive driving there is theconcept of defensive programming , i.e. “the best defense is a good offense”.
my definition of defensive programming is to use techniques to construct the code so that the pathways are simple and easy to understand. put your effort into writing defect free code, not on debugging code with defects.
in addition, if i can make the program aware of its context when a problem occurs then it should halt and prompt me with an error message so that i know exactly what happened.
there are far too many defensive programming techniques to cover them all here, so let's hit just a few that i like (send me your favoritetechniques email ):
- proper use of exceptions
- decision tables
- design by contract
- automated tests
proper use of exceptions
// program should not get here
any developer who writes a comment like this should be shot . after all, what if you are wrong and the program really gets there? this situation exists in most programs especially for the default case of a case/switch statement.
your comment is not going to stop the program and itwill probably go on to create a defect or side effect somewhere else.
it could take you a long time to figure out what the root cause of the eventual defect; especially since you may be thrown off by your own comment and not consider the possibility of the code getting to that point.
of course you should at least log the event, but this article is about debuggers and not debugging – so let’s leave thediscussion about logging until the end of the article.
at a minimum you should replace the comment with thef ollowing:
throw new exception( “program should not get here!”);
assuming that you have access to exceptions . but even this is not going far enough; after all, you have information about the conditions that must be true to get to that location. the exception shouldreflect those conditions so that you understand immediately what happened ifyou see it.
for example, if the only way to get to that place in thecode is because the customer object is inconsistent then the following isbetter:
throw new inconsistentcustomerexception( “new event date preceeds creation date for customer ” + customer.getidentity() );
if the inconsistentcustomerexception is ever thrown then you will probably have enough information to fix the defect as soon as you see it.
improper design of code pathways has other incarnations, such as not planning enough code pathways in complex logic . i.e. you build code with 7 code pathways but you really need 8 pathways to handle all inputs. any data that requires the missing 8 th pathway will turn into a calculation error or improper persistent data adjustment and cause a problem somewhere else in the code.
when you have complex sections of code with multiple pathways then create a decision table to help you to plan the code.
decision tables have been around since the 1960s, they areone of the best methods for pro-actively designing sections of code that are based on complex decisions . (aside: sdn is based on decision tables, so this is still relevant)
however, don't include the decision table in a comment unless you plan to keep it up to date (see comments are for losers ).
design by contract
the concept of design by contract (dbc) was introduced in 1986 by the eiffel programming language . i realize that few people program in eiffel, but the concept can be applied to any language. the basic idea is that every class function should have pre-conditions and post-conditions that are tested on every execution.
the pre-conditions are checked on the entry to the function and the post-conditions are checked on the exit to the function. if any of the conditions are violated then you would throw an exception .
dbc is invasive and adds overhead to every call in your program. let's see what can make this overhead worth it. when we write programs, the call stack can be quite deep.
let's assume we have the following call structure; as you can see h can be reached through different call paths (i.e. throughanyone calling f or g ).
let's assume that the call flow from a has a defect that needs to be fixed in h , clearly that will affect the call flow from b .
if the fix to h will cause a side effect to occur inf, then odds are the dbc post conditions of f (or b ) will catchthe problem and throw an exception.
contrast this with fixing a problem with no checks and balances. the side effect could manifest pretty far away from the problem was created and cause intermittent problems that are very hard to track down.
dbc via aspect oriented programming
clearly very few of us program in eiffel. if you have access to aspect oriented programming (aop) then you can implement dbc via aop. today thereare aop implementations as a language extension or as a library for many current languages (java, .net, c++, php, perl, python, ruby, etc).
normal application use will exercise few code pathways in day to day application use. for every normal code pathway there will be several alternative pathways to handle exceptional processing, and this is where most defects willbe found.
some of these exceptions do not happen very often because they will involve less than perfect input data – do you really want those exceptions to happen for the first time on a remote customer system for which you have few troubleshooting tools?
if you are using test driven development (tdd) then you already have a series of unit tests for all your code. the idea is good, but does not go far enough in my opinion.
automated tests should not only perform unit tests but also perform tests at the integration level. this will not only test your codewith unusual conditions at the class level but also at the integration level between classes and modules. ultimately these tests should be augmented with the use of a canonical database where you can test data side effects as well.
the idea is to build up your automated tests until the code coverage gets in the 80%+ category. getting to 80%+ means that your knowledge of the system pathways will be very good and the time required for defect fixing should fall dramatically.
why 80%+? (see minimum acceptable code coverage )
if you can get to 80%+ it also means that you have a prettygood understanding of your code pathways. the advantage to code coverage testing is that it does not affect the runtime performance of your code and it improves your understanding of the code.
all your defects are hiding in the code that you don't test.
reducing dependence on debuggers
if you have to resort to a debugger to find a defect then take a few minutes after you solve the problem and ask, " was there a faster way? ". what did you learn from using the debugger? is there something that you can do to prevent you (or someone else) having to use the debugger down this same path again? would refactoring the code or putting in a better exception help?
the only way to resolve a defect is by understanding what is happening in your code. so the next time you have a defect to chase down,start by thinking about the problem. spend a few minutes and see if you can't resolve the issue before loading up the debugger.
another technique is to discuss the source of a defect with another developer. even if they are not familiar with your codethey will prompt you with questions that will quite often help you to locate the source of the defect without resorting to the debugger.
in several companies i convinced the developers to forgo using their debuggers for a month. we actually deleted the code for the debuggers on everyones system. this drastic action had the effect of forcing the developers to think about how defects were caused. developers complainedfor about 2 weeks, but within the month their average time to find a defect had fallen over 50% .
try to go a week without your debugger, what have you got to lose?
after all, the next graph shows how much effort we spend trying to remove defects, the average project ends up spending 30% of the total time devoted to defect removal. imagine what a 50% boost in efficiency will do foryour project? the yellow zone sketches out where most projects fall.
|function points||average effort|
|10||1 man month|
|100||7 man month|
|1000||84 man month|
|10000||225 man year|
there will definitely be times where a debugger will be the best solution to finding a problem.
while you are spending time in the debugger your project is on hold , it will not progress.
some programs have complex and convoluted sections that generate many defects. instead of running through the sections with the debugger you should perform a higher level analysis of the code and rewrite the problematic section.
if you find yourself going down the same code pathways multiple times in the debugger then you might want to stop and ask yourself," is there a better way to do this? "
as master card might say, " not using the debugger... priceless ".
want to see more sacred cows get tipped? check out:
Published at DZone with permission of Dalip Mahal, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.