debugging - hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. design an...

22
Debugging BBM 101 - Introduc/on to Programming I Hace7epe University Fall 2015 Fuat Akal, Aykut Erdem, Erkut Erdem, Vahid Garousi 1 Slides based on material prepared by Ruth Anderson, Michael Ernst and Bill Howe in the course CSE 140 University of Washington

Upload: others

Post on 22-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

Debugging

BBM101-Introduc/ontoProgrammingI

Hace7epeUniversityFall2015

FuatAkal,AykutErdem,ErkutErdem,VahidGarousi

1SlidesbasedonmaterialpreparedbyRuthAnderson,MichaelErnstandBillHoweinthecourseCSE140UniversityofWashington

Page 2: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

Example:WriteaFunc5on

Writeafunc/onthatwillreturnthesetofauser’sfriendswithapar/cularuserremovedfromthatset.

2

Page 3: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

TheProblem

Whatyouwantyourprogramtodo

Whatyourprogramdoes

Notthesame!

3

Thereisabug!

Page 4: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

WhatisDebugging?

•  GraceHopperwasoneofU.S.’sfirstprogrammers.•  ShefoundamothintheMarkIcomputer,whichwascausingerrors,andcalleditacomputer“bug”

•  Thus,theworddebuggingiscoinedJ

4

Page 5: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DebuggingTools

•  Pythonerrormessage•  assert •  print •  Pythoninterpreter•  PythonTutor(h7p://pythontutor.com)•  Pythondebugger•  Besttool:

5

Page 6: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

TwoKeyIdeas1.  Thescien/ficmethod2.  DivideandconquerIfyoumasterthose,youwillfinddebuggingeasy,andpossiblyenjoyable;-)

6

Page 7: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

TheScien5ficMethod1.  Createahypothesis2.  Designanexperimenttotestthathypothesis

–  Ensurethatityieldsinsight3.  Understandtheresultofyourexperiment

–  Ifyoudon’tunderstand,thenpossiblysuspendyourmainlineofworktounderstandthat

Tips:•  Besystema/c

–  Neverdoanythingifyoudon'thaveareason–  Don’tjustflail

•  Randomguessingislikelytodigyouintoadeeperhole•  Don’tmakeassump/ons(verifythem)

7

Page 8: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

ExampleExperiments

1.  Analternateimplementa/onofafunc/on– Runallyourtestcasesaferward

2.  Anew,simplertestcase– Examples:smallerinput,ortestafunc/oninisola/on

– Canhelpyouunderstandthereasonforafailure

8

Page 9: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

YourScien5ficNotebookRecordeverythingyoudo•  Specificinputsandoutputs(bothexpectedandactual)•  Specificversionsoftheprogram

–  Ifyougetstuck,youcanreturntosomethingthatworks–  Youcanwritemul/pleimplementa/onsofafunc/on

•  Whatyouhavealreadytried•  Whatyouareinthemiddleofdoingnow

–  Thismaylooklikeastack!•  Whatyouaresureof,andwhyYournotebookalsohelpsifyouneedtogethelporreproduceyourresults

9

Page 10: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

ReadtheErrorMessageTraceback (most recent call last): File "nx_error.py", line 41, in <module> print friends_of_friends(rj, myval) File "nx_error.py", line 30, in friends_of_friends f = friends(graph, user) File "nx_error.py", line 25, in friends return set(graph.neighbors(user))# File "/Library/Frameworks/…/graph.py", line 978, in neighbors return list(self.adj[n]) TypeError: unhashable type: 'list' Listofallexcep/ons(errors):h7p://docs.python.org/2/library/excep/ons.html#bl/n-excep/onsTwootherresources,withmoredetailsaboutafewoftheerrors:h7p://inventwithpython.com/appendixd.htmlh7p://www.cs.arizona.edu/people/mccann/errors-python

Callstackortraceback

Firstfunc/onthatwascalled(<module> meanstheinterpreter)

Secondfunc/onthatwascalled

Lastfunc/onthatwascalled(thisonesufferedanerror)

Theerrormessage:daun/ngbutuseful.Youneedtounderstand:•  theliteralmeaningof

theerror•  theunderlying

problemscertainerrorstendtosuggest

10

Page 11: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

CommonErrorTypes•  Asser/onError

–  Raisedwhenanassertstatementfails.

•  IndexError–  Raisedwhenasequencesubscriptisoutofrange.

•  KeyError–  Raisedwhenamapping(dic/onary)keyisnotfoundinthesetofexis/ngkeys.

•  KeyboardInterrupt–  Raisedwhentheuserhitstheinterruptkey(normallyControl-CorDelete).

•  NameError–  Raisedwhenalocalorglobalnameisnotfound.

•  SyntaxError–  Raisedwhentheparserencountersasyntaxerror.

•  Indenta/onError–  Baseclassforsyntaxerrorsrelatedtoincorrectindenta/on.

•  TypeError–  Raisedwhenanopera/onorfunc/onisappliedtoanobjectofinappropriatetype. 11

Page 12: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DivideandConquer•  Whereisthedefect(or“bug”)?•  Yourgoalistofindtheoneplacethatitis•  Findingadefectisofenharderthanfixingit

•  Ini/ally,thedefectmightbeanywhereinyourprogram–  Itisimprac/caltofinditifyouhavetolookeverywhere

•  Idea:bitbybitreducethescopeofyoursearch•  Eventually,thedefectislocalizedtoafewlinesoroneline

–  Thenyoucanunderstandandfixit

•  4waystodivideandconquer:–  Intheprogramcode–  Intestcases–  Duringtheprogramexecu/on–  Duringthedevelopmenthistory

12

Page 13: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DivideandConquerintheProgramCode

•  Localizethedefecttopartoftheprogram–  e.g.,onefunc/on,oronepartofafunc/on

•  Codethatisn’texecutedcannotcontainthedefect

3approaches:•  Testonefunc/onata/me•  Addasser/onsorprintstatements

–  Thedefectisexecutedbeforethefailingasser/on(andmaybeaferasucceedingasser/on)

•  SplitcomplexexpressionsintosimpleronesExample:Failurein result = set({graph.neighbors(user)}) Changeitto nbors = graph.neighbors(user) nbors_set = {nbors} result = set(nbors_set) Theerroroccursonthe“nbors_set={nbors}"line

13

Page 14: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DivideandConquerinTestCases

•  Yourprogramfailswhenrunonsomelargeinput–  It’shardtocomprehendtheerrormessage–  Thelogofprintstatementoutputisoverwhelming

•  Tryasmallerinput–  Chooseaninputwithsomebutnotallcharacteris/csofthelargeinput

–  Example:duplicates,zeroesindata,…

14

Page 15: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DivideandConquerinExecu5onTimeviaPrint(or“logging”)Statements

•  Asequenceofprintstatementsisarecordoftheexecu/onofyourprogram

•  Theprintstatementsletyouseeandsearchmul/plemomentsin/me

•  Printstatementsareausefultechnique,inmodera/on•  Bedisciplined–  Toomuchoutputisoverwhelmingratherthaninforma/ve–  Rememberthescien/ficmethod:haveareason(ahypothesistobetested)foreachprintstatement

–  Don’tonlyuseprintstatements

15

Page 16: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

DivideandConquerinDevelopmentHistory

•  Thecodeusedtowork(forsometestcase)•  Thecodenowfails•  Thedefectisrelatedtosomelineyouchanged

•  Thisisusefulonlyifyoukeptaversionofthecodethatworked(usegoodnames!)

•  Thisismostusefulifyouhavemadefewchanges•  Moral:testofen!–  Fewerlinestocompare–  Yourememberwhatyouwerethinking/doingrecently

16

Page 17: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

AMetaphorAboutDebuggingIfyourcodedoesn’tworkasexpected,thenbydefini/onyoudon’tunderstandwhatisgoingon.•  You’relostinthewoods.•  You’rebehindenemylines.•  Allbetsareoff.•  Don’ttrustanyoneoranything.Don’tpressonintounexploredterritory--gobackthewayyoucame!(andleavebreadcrumbs!)

You’retryingto“advancethefrontlines,”not“trailblaze”17

Page 18: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

Time-SavingTrick:MakeSureYouareDebuggingtheRightProblem

•  Thegameistogofrom“workingtoworking”•  Whensomethingdoesn’twork,STOP!

–  It’swildoutthere!•  FIRST:Gobacktothelastsitua/onthatworkedproperly.

–  Rollbackyourrecentchangesandverifythateverythings/llworksasexpected.

–  Don’tmakeassump/ons–bydefini/on,youdon’tunderstandthecodewhensomethinggoeswrong,soyoucan’ttrustyourassump/ons.

–  Youmayfindthatevenwhatpreviouslyworkednowdoesn’t–  Perhapsyouforgottoconsidersome“innocent”oruninten/onalchange,

andnoweventestedcodeisbroken

18

Page 19: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

ABadTimeline

•  Aworks,socelebrateali7le•  NowtryB•  Bdoesn’twork•  ChangeBandtryagain•  ChangeBandtryagain•  ChangeBandtryagain…

19

Page 20: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

ABeSerTimeline•  Aworks,socelebrateali7le•  NowtryB•  Bdoesn’twork•  RollbacktoA•  DoesAs/llwork?

–  Yes:FindA’thatissomewherebetweenAandB–  No:Youhaveuninten=onallychangedsomethingelse,andthere’sno

pointfutzingwithBatall!

These“innocent”andunno/cedchangeshappenmorethanyouwouldthink!•  Youaddacomment,andtheindenta/onchanges.•  Youaddaprintstatement,andafunc/onisevaluatedtwice.•  Youmoveafile,andthewrongoneisbeingread•  Youareonadifferentcomputer,andthelibraryisadifferentversion

20

Page 21: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

OnceYouareonSolidGroundYoucanSetOutAgain

•  Onceyouhavesomethingthatworksandsomethingthatdoesn’twork,itisonlyama7erof/me

•  Youjustneedtoincrementallychangetheworkingcodeintothenon-workingcode,andtheproblemwillrevealitself.

•  Varia/on:Perhapsyourcodeworkswithoneinput,butfailswithanother.Incrementallychangethegoodinputintothebadinputtoexposetheproblem.

21

Page 22: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the

SimpleDebuggingTools

print–  showswhatishappeningwhetherthereisaproblemornot

–  doesnotstopexecu/onassert–  Raisesanexcep/onifsomecondi/onisnotmet–  Doesnothingifeverythingworks–  Example:assert len(rj.edges()) == 16 –  Usethisliberally!Notjustfordebugging!

22