Debugging Building Rock-Solid Software Software University Technical Trainers SoftUni Team.

Download Debugging Building Rock-Solid Software Software University Technical Trainers SoftUni Team.

Post on 11-Jan-2016




3 download

Embed Size (px)



DebuggingBuilding Rock-Solid Software

Software Universityhttp://softuni.bgTechnical TrainersSoftUni TeamTable of ContentsIntroduction to DebuggingVisual Studio DebuggerBreakpointsData InspectionFinding a Defect2

Introduction to Debugging

The process of locating and fixing or bypassing bugs (errors) in computer program codeTo debug a program:Start with a problemIsolate the source of the problemFix itDebugging tools (called debuggers) help identify coding errors at various development stagesWhat is Debugging?5TestingA means of initial detection of errorsDebuggingA means of diagnosing and correcting the root causes of errors that have already been detectedDebugging vs. Testing

Some programmers use the terms "testing" and "debugging" interchangeably, but careful programmers distinguish between the two activities. Testing is a means of detecting errors. Debugging is a means of diagnosing and correcting the root causes of errors that have already been detected.56$60 Billion per year in economic losses due to software defectsPerfect code is an illusionThere are factors that are out of our controlLegacy codeYou should be able to debug code that is written years agoDeeper understanding of system as a wholeImportance of Debugging7Debugging can viewed as one big decision treeIndividual nodes represent theoriesLeaf nodes represent possible root causesTraversal of tree boils down to process state inspectionMinimizing time to resolution is keyCareful traversal of the decision treePattern recognitionVisualization and ease of use helps minimize time to resolutionDebugging Philosophy8Example Debugging - Decision TreeOutOfMemoryExceptionNative Heaps?Virtual?.NET Heaps?.NET Types?Native?Native Heaps?Long references? Visual Studio Debugger

Visual Studio IDE gives us a lot of tools to debug your applicationAdding breakpointsVisualize the program flowControl the flow of executionData tipsWatch variablesDebugging multithreaded programsand many moreVisual Studio Debugger11Starting a process under the Visual Studio debuggerAttaching to an already running processWithout a solution loaded you can still debugUseful when solution isn't readily availableDebug menu -> Attach to ProcessHow To Debug a Process

12Debug menu, Start Debugging itemF5 is a shortcutEasier access to the source code and symbols since its loaded in the solutionCertain differences exist in comparison to debugging an already running processHosting for ASP.NET applicationVS uses a replacement of the real IISDebugging a SolutionDebug Windows are the means to introspect on the state of a processOpens a new window with the selected information in itWindow categoriesData inspectionThreadingAccessible from menuDebug -> WindowsDebug Windows

14Convenient shortcut to common debugging tasksStep intoStep overContinueBreakBreakpointsCustomizable to fit your needsAdd / Remove buttonsDebugging Toolbar

15By default, an app will run uninterrupted (and stop on exception or breakpoint)Debugging is all about looking at the state of the processControlling execution allows:Pausing executionResuming executionStepping through the application in smaller chunksIn the case of IntelliTrace (recording steps), allows backward and forward steppingControlling Execution16IntelliTrace operates in the background, records what you are doing during debuggingYou can easily get a past state of your application from IntelliTraceYou can navigate through your code and see what's happenedTo navigate, just click any of the eventsthat you want toexploreIntelliTrace

17Visual Studio offers quite a few knobs and tweaks in the debugging experienceOptions and settings is available via Debug -> Options and SettingsExamples of Options and SettingsEnable just my code (ignore other code)Enable .NET framework source steppingSource server supportSymbols (line numbers, variable names)Much moreOptions and SettingsBreakpoints

Ability to stop execution based on certain criteria is key when debuggingWhen a function is hitWhen data changesWhen a specific thread hits a functionMuch moreVisual Studio's debugger has a huge feature set when it comes to breakpointsBreakpoints20Stops execution at a specific instruction (line of code)Can be set using Debug->Toggle breakpointF9 shortcutClicking on the left most side of the source code windowBy default, the breakpoint will hit every time execution reaches the line of the codeAdditional capabilities: condition, hit count, value changed, when hit, filtersVisual Studio Breakpoints21Managed in the breakpoint windowAdding breakpointsRemoving or disabling breakpointsLabeling or grouping breakpointsExport/import breakpointsManaging Breakpoints

22Allows you to excerpt even more control of when a breakpoint hitsExamples of customizationMachine nameProcess IDProcess nameThread IDThread nameMultiple can be combined using &, ||, !Breakpoint Filters

Data Inspection

Debugging is all about data inspectionWhat are the local variables?What is in memory?What is the code flow?In general - What is the state of the process right now and how did it get there?As such, the ease of data inspection is key to quick resolution of problemsData Inspection25Visual Studio offers great data inspection featuresWatch windowsAutos and LocalsMemory and RegistersData TipsImmediate windowVisual Studio Data Inspection

26Allows you to inspect various states of your applicationSeveral different kinds of "predefined" watch windowsAutosLocals"Custom" watch windows also possibleContains only variables that you choose to addRight click on the variable and select "Add to Watch"Watch Window27Locals watch window contains the local variables for the specific stack frameDebug -> Windows -> LocalsDisplays: name of the variable, value and typeAllows drill down into objects by clicking on the + sign in the tree controlAutos lets the debugger decide which variables to show in the windowLoosely based on the current and previous statementAutos and Locals28Memory window can be used to inspect process wide memoryAddress field can be a raw pointer or an expressionDrag and drop a variable from the source windowNumber of columns displayed can be configuredData format can be configuredRegisters window can be used to inspect processor registersMemory and Registers29Provides information about variablesVariables must be within scope of current executionPlace mouse pointer over any variableVariables can be expanded by using the + signPinning the data tip causes it to always stay openComments can be added to data tipsData tips support drag and dropImporting and exporting data tipsData Tips30Useful when debugging due to the expansive expressions that can be executedTo output the value of a variable To set values, use =To call a method, use .(arguments)Similar to regular codeSupports IntelliSenseImmediate Window

Threads and Stacks

32Fundamental units of code executionCommonly, programs use more than one threadIn .NET, there is always more than one threadEach thread has a memory area associated with it known as a stackStores local variablesStores frame specific informationMemory area employs last in first out semanticsThreads33Contains an overview of thread activity in the processIncludes basic information in a per thread basisThread ID'sCategoryNameLocationPriorityThreads Window

34A threads stack is commonly referred to as a callstackVisual Studio shows the elements of a callstackLocal variablesMethod frames


Finding a Defect

36Stabilize the errorLocate the source of the errorGather the dataAnalyze the data and form hypothesisDetermine how to prove or disprove the hypothesisProve or disprove the hypothesis by 2c)Fix the defectTest the fixLook for similar errorsFinding a Defect

37Use all available dataRefine the test casesCheck unit testsUse available toolsReproduce the error several different waysGenerate more data to generate more hypothesesUse the results of negative testsBrainstorm for possible hypothesesTips for Finding Defects

38Narrow the suspicious region of the codeBe suspicious of classes and routines that have had defects beforeCheck code that's changed recentlyExpand the suspicious region of the codeIntegrate incrementallyCheck for common defectsTalk to someone else about the problemTake a break from the problem

Tips for Finding Defects (2)

39Understand the problem before you fix itUnderstand the program, not just the problemConfirm the defect diagnosisRelaxSave the original source codeFix the problem, not the symptomMake one change at a timeAdd a unit test that expose the defectLook for similar defectsFixing a Defect

Source: http://www.movingseniorsbc.com3940Your ego tells you that your code is good and doesn't have a defect even when you've seen that it has.How "Psychological Set" Contributes to Debugging BlindnessPsychological Considerations Refactoring

Questions?????????? Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.41LicenseThis course (slides, examples, demos, videos, homework, etc.)is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license42

Attribution: this work may contain portions from"High Quality Code" course by Telerik Academy under CC-BY-NC-SA license Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.42Free Trainings @ Software UniversitySoftware University Foundation softuni.orgSoftware University High-Quality Education, Profession and Job for Software Software University @ University @ University Forums

Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.43


View more >