20

Debugging !!! ► Believe it or not, errors happen ► The most frustrating part of programming ► Hunting down an error can be harder and more time consuming

Embed Size (px)

Citation preview

Debugging !!! Debugging !!!

► Believe it or not, errors happenBelieve it or not, errors happen► The most frustrating part of programmingThe most frustrating part of programming► Hunting down an error can be harder and Hunting down an error can be harder and

more time consuming than the solution to more time consuming than the solution to the original problemthe original problem

► Debugging tools and methodologies are still Debugging tools and methodologies are still in their infancyin their infancy

► It’s still an art form: must be done manuallyIt’s still an art form: must be done manually► Can’t tell you how to be Da Vinci, but can Can’t tell you how to be Da Vinci, but can

certainly give you a brush and some paintcertainly give you a brush and some paint

Just use a debugger!Just use a debugger!

►Unfortunately, we don’t live in that Unfortunately, we don’t live in that perfect world just yetperfect world just yet

►Several problems with debuggers:Several problems with debuggers: May not be available for several reasonsMay not be available for several reasons Don’t work for complex systems like Don’t work for complex systems like

distributed computingdistributed computing It’s just plain confusing sometimesIt’s just plain confusing sometimes

►Can be thought of more as reverse Can be thought of more as reverse engineering than a straight forward engineering than a straight forward processprocess

MethodologyMethodology

►Use your brain… not your fingersUse your brain… not your fingers►Keep it simple initiallyKeep it simple initially

Look for simple solutions firstLook for simple solutions first The most likely culprit will usually be itThe most likely culprit will usually be it

►Move on to more complex solutionsMove on to more complex solutions►For the most part, try and assume the For the most part, try and assume the

computer is doing its job. It’s not wrongcomputer is doing its job. It’s not wrong►There are different kinds of bugs to look There are different kinds of bugs to look

forfor

Kinds of ErrorsKinds of Errors

► Compile time errorsCompile time errors Usually pointed out to you, easy to fixUsually pointed out to you, easy to fix Syntactical errorsSyntactical errors

► Run time errorsRun time errors ““System Errors”: Out of bounds, class cast System Errors”: Out of bounds, class cast

exception, null pointer exceptionexception, null pointer exception ““Logic Errors”: No visible errors, you just get the Logic Errors”: No visible errors, you just get the

wrong answerwrong answer

► Causes of ErrorsCauses of Errors Flawed Logic (semantics)Flawed Logic (semantics) Typos (syntactical)Typos (syntactical)

Thought ProcessThought Process

► Its not working… now what?Its not working… now what?►Make sure it is actually a bugMake sure it is actually a bug►Was your solution model flawed?Was your solution model flawed?►Are you printing what you want to print?Are you printing what you want to print?►Did you forget to save / correct version?Did you forget to save / correct version?►Libraries are up to date?Libraries are up to date?►Did you forget to end a comment?Did you forget to end a comment?►Was there a crucial input missing?Was there a crucial input missing?

Easy Bugs: Lots of CluesEasy Bugs: Lots of Clues

► How to look for clues?How to look for clues?► Tip: Avoid writing too much before runningTip: Avoid writing too much before running► Did a recent change break the code?Did a recent change break the code?► Have you seen this bug before? What did you Have you seen this bug before? What did you

do in the past to fix it?do in the past to fix it?► Think first, write down on paper what is going Think first, write down on paper what is going

onon► A second set of eyes might be able to see what A second set of eyes might be able to see what

you are missing. You have been staring at it so you are missing. You have been staring at it so long you might miss something simple.long you might miss something simple.

More complex problemsMore complex problems

► Might be system specific, check manualsMight be system specific, check manuals► Narrow down inputs which reproduce the Narrow down inputs which reproduce the

bug. If you know which inputs make it fail bug. If you know which inputs make it fail you can pinpoint where the error may be.you can pinpoint where the error may be.

► Are you close to data type limits?Are you close to data type limits?► Look for suspicious values: Powers of 2, weird Look for suspicious values: Powers of 2, weird

ASCII (more applicable in other languages)ASCII (more applicable in other languages)► Are your data structures valid?Are your data structures valid?► Does taking out bits of code make it work?Does taking out bits of code make it work?► Inserting print statements…Inserting print statements…

Foreign/Old CodeForeign/Old Code

► Get a copy of the design / problem statementGet a copy of the design / problem statement► Work it out by hand firstWork it out by hand first► Group their functions into small bits of readable Group their functions into small bits of readable

English: “Formats text”, “Convert hex to binary”English: “Formats text”, “Convert hex to binary”► Know what it all does before attempting to fix itKnow what it all does before attempting to fix it► Sadly: Complete rewrites often faster than Sadly: Complete rewrites often faster than

debugging other people’s code debugging other people’s code ► Look for examples of ‘hard coding’: declared Look for examples of ‘hard coding’: declared

strings, integers, counters which are defined strings, integers, counters which are defined instead of read as inputinstead of read as input

The Art of Print StatementsThe Art of Print Statements

► System.out.println(“UUUUUUUUUUUUUGH”);System.out.println(“UUUUUUUUUUUUUGH”);► System.out.println(“YESSSSSSSSSSSSSSSS”);System.out.println(“YESSSSSSSSSSSSSSSS”);► Usually best way to find errors in small systems, Usually best way to find errors in small systems,

especially number-basedespecially number-based► Things to printThings to print

Counter valuesCounter values Min/Max valuesMin/Max values Array indicesArray indices Data structure valuesData structure values

► Where to printWhere to print Before / after declarations/initializationsBefore / after declarations/initializations Before / after function callsBefore / after function calls Before / after entering loops / recursionBefore / after entering loops / recursion Before “breaking” from a loopBefore “breaking” from a loop

Java SpecificJava Specific

►Always give your objects a .toString() or a Always give your objects a .toString() or a .toDebug() method.toDebug() method

►Make use of Arrays.toString() etcMake use of Arrays.toString() etc►print(Index + “ : “ + value) in loopsprint(Index + “ : “ + value) in loops►Use iterators where possibleUse iterators where possible► Instead of setting your own parameters Instead of setting your own parameters

for a prebuilt class, override itfor a prebuilt class, override it► If building GUI/JS, use System.err.println()If building GUI/JS, use System.err.println()

ExamplesExamples► NullPointerExceptionsNullPointerExceptions

Print statement after initialization or immediately Print statement after initialization or immediately before passing into functionsbefore passing into functions

► ArrayOutOfBoundsArrayOutOfBounds Lucky if you are using java that they are thrownLucky if you are using java that they are thrown Print index counters, array valuesPrint index counters, array values

► Infinite LoopsInfinite Loops Do searches for index counter names/updatesDo searches for index counter names/updates

► ““Wrong answers”Wrong answers” Go over it again by hand, your solution probably is Go over it again by hand, your solution probably is

not correct in the first place. Put the code on holdnot correct in the first place. Put the code on hold

Example: MathematicsExample: Mathematics

►Sine and Cosine mixed up?Sine and Cosine mixed up?►Negative values?Negative values?►Values close to zero / rounding errors?Values close to zero / rounding errors?►Adding small values to large valuesAdding small values to large values►Reversing min / max values?Reversing min / max values?►Pass by reference / value?Pass by reference / value?►Loops correct?Loops correct?

Examples (ctd)Examples (ctd)►Loops / ConditionalsLoops / Conditionals►Are your counters in the right order?Are your counters in the right order?►++counter vs. counter++++counter vs. counter++►Multi dimensional – do it by hand firstMulti dimensional – do it by hand first►Make sure bracketing matches with Make sure bracketing matches with

indentingindenting►Copy / Paste changesCopy / Paste changes

Life Lessons…Life Lessons…

►Format of a file is not standard asciiFormat of a file is not standard ascii►Format of a file is little endian instead Format of a file is little endian instead

of big endianof big endian►Naming conventions actually matter in Naming conventions actually matter in

fortranfortran►Programming in C for the first time – Programming in C for the first time –

arrays do not initializearrays do not initialize

Reverse EngineeringReverse Engineering

►Start from the error and work backwardsStart from the error and work backwards►Make sure all your parts work before Make sure all your parts work before

testing the system as a wholetesting the system as a whole►Surround the affected area with output Surround the affected area with output

information / line breaksinformation / line breaks►Edit lines of ‘fluff’ code out to test the Edit lines of ‘fluff’ code out to test the

‘meat’‘meat’►Experiment with different input valuesExperiment with different input values►Fix the code line by lineFix the code line by line

DebuggerDebugger

► Built into Eclipse for javaBuilt into Eclipse for java► GUI / Text based, same ideaGUI / Text based, same idea► Only used as a last resort, very time Only used as a last resort, very time

consumingconsuming► Allow for insertion of break lines to halt code Allow for insertion of break lines to halt code

execution at any pointexecution at any point► Allow you to see the contents of any object / Allow you to see the contents of any object /

array / primitive at any time by queryarray / primitive at any time by query► Amount of data shown often overwhelmingAmount of data shown often overwhelming► Doesn’t provide insight into logical errorDoesn’t provide insight into logical error► Still a manual process to find errorsStill a manual process to find errors

How to avoidHow to avoid

►Don’t write 1000 lines before testingDon’t write 1000 lines before testing►Variable names can have meaningVariable names can have meaning►Don’t hard code ANYTHING. If you must, Don’t hard code ANYTHING. If you must,

define all of them in the same place define all of them in the same place where they are easily seen / changedwhere they are easily seen / changed

►Comment everywhere it isn’t obviousComment everywhere it isn’t obvious► If its more than a few lines… put it in a If its more than a few lines… put it in a

functionfunction►Always use { }Always use { }

Personal Horror StoriesPersonal Horror Stories► if (conditional which ran longer than the width of my screen); if (conditional which ran longer than the width of my screen);

break;break;► while (index < end)while (index < end)

go from the end of a string to the front…go from the end of a string to the front…

index = index -1;index = index -1;► for (int i=0; i<x; i++) for (int j=0; j<y; i++)for (int i=0; i<x; i++) for (int j=0; j<y; i++)► Forgot about a hard coded n*n matrix readForgot about a hard coded n*n matrix read► Drew background last in graphics classDrew background last in graphics class► Spent 4 hours debugging because C didn’t flush a bufferSpent 4 hours debugging because C didn’t flush a buffer► Tried to do anything in fortran or prologTried to do anything in fortran or prolog