Tải bản đầy đủ - 0 (trang)
Chapter 23. Preemptive Error Detection with FindBugs

Chapter 23. Preemptive Error Detection with FindBugs

Tải bản đầy đủ - 0trang

Maryland.Itusesstaticcodeanalysistodetectpotentialbugs

usingthenotionof"bugpatterns."Bugpatternsarepoor

codingpracticesthataregenerallyincorrectandmayleadto

applicationerrors.Forexample,inthefollowingcode,ifthe

addressvariableisnull,thesecondlinewillgeneratea

NullPointerException:

Addressaddress=client.getAddress();

if((address!=null)||(address.getPostCode()!=null)){

...

}



Anotherexampleisshownhere,inwhichtheitemsmember

variableisaccessedwithouthavingbeeninitialized:

publicclassShoppingCart{

privateListitems;

publicaddItem(Itemitem){

items.add(item);

}

}



Errorsliketheseareofteneasytoidentifysimplybyreadingthe

code.However,althougheffective,codereviewsarelaborintensiveandtime-consuming,andwhereverpossibleitis

easiertoletthemachinedotheinspectionforyou!FindBugsis

designedtodojustthat.

FindBugsusestheApacheBCELlibrarytoanalyzetheclassesin

yourapplicationanddetectpotentialbugs.FindBugsrules(or

"detectors")useavarietyofinspectiontechniques,from

examiningthestructureoftheclassrightthroughtostudying

thedetaileddataflowthroughtheclass.Inadditiontothe

detectorsprovidedbyFindBugs,withabitofwork,youcan



writeyourowncustom-builtdetectors.

FindBugscomeswithover200rulesdividedintodifferent

categories:



Correctness



Theseissuesinvolvecodethatisprobablyincorrect

insomeway,forexample,codethatinvolvesan

infiniterecursivelooporthatreadsafieldthatis

neverwritten.Issuesinthiscategoryarealmost

certainlybugs.



Badpractice



AccordingtotheFindBugsteam,issuesinthis

categoryinvolve"clearviolationofrecommended

andstandardcodingpractice."Thebadpractices

thatFindBugsisinterestedingenerallyhavea

directcorrelationwithpotentialdefects,for

example,codethatdropsexceptionsorfailstoclose

fileordatabaseresources.Someoftheseissuesare

alsodetectedbyPMD.



Performance



Theseissuesaimatdetectingpotentialperformance

issues,suchascodeinvolvingunnecessaryobject

creation,orusingstringconcatenationinaloop

ratherthanusingaStringBuffer.



Multithreadedcorrectness



Theseisaspecialcategoryofissuesinvolving

problemswithsynchronizedandmultithreaded

code.



Dodgy



Thistypeofissueinvolvescodewhichseemsodd,

or"smellsbad,"inXPterminology,suchasunused

localvariablesoruncheckedcasts.Accordingtothe

FindBugsteam,lessthanhalfoftheseissues

involveactualbugs.

FindBugscanbeusedinthreeways;asastandaloneSwing

application,inEclipseusingtheEclipseplug-in,orintegrated

intothebuildprocessasanAnttaskorMavenreport.In

practice,thestandaloneapplicationisrarelyused:developers

prefertobeabletoinvokeFindBugsdirectlyfromwithintheir

workenvironment,whereasprojectmanagersandquality

assurancepeopleappreciatebeingabletodisplayproject-wide

bugreportsusingthereportingfeatures.

Intherestofthischapter,wewilllookathowtouseFindBugs

inthesedifferentcontexts.



Chapter23.PreemptiveErrorDetection

withFindBugs

FindBugs:ASpecializedBugKiller

UsingFindBugsinEclipse

SelectivelySuppressingRuleswithFindBugFilters

UsingFindBugsAnnotations

UsingFindBugsinAnt

UsingFindBugsinMaven

Conclusion



23.1.FindBugs:ASpecializedBugKiller

FindBugsisanotherstaticanalysistoolforJava,similarinsome

waystoCheckstyle(seeChapter21)andPMD(seeChapter

22),butwithaquitedifferentfocus.FindBugsisnotconcerned

byformattingorcodingstandardsandonlymarginally

interestedinbestpractices:infact,itconcentratesondetecting

potentialbugsandperformanceissues.Itdoesaverygoodjob

offindingthese,andcandetectmanytypesofcommon,hardto-findbugs.Indeed,FindBugsiscapableofdetectingquitea

differentsetofissuesthanPMDorCheckstylewitharelatively

highdegreeofprecision.Assuch,itcanbeausefuladditionto

yourstaticanalysistoolbox.

FindBugswaswritteninresponsetotheoverwhelmingnumber

ofissuesraisedbyothertoolssuchasCheckstyleandPMD.

Manyoftheissuesraisedbythesetoolsareactuallyfalse

positivesandbothtoolsneedtobefine-tunedtoavoidreal

issuesbeinghiddenbytoomanyfalsepositives.FindBugstries

hardtoconcentrateonidentifyingonlyissuesthatinvolve

genuinepotentialcodingerrors.

FindBugsistheresultofaresearchprojectattheUniversityof



Maryland.Itusesstaticcodeanalysistodetectpotentialbugs

usingthenotionof"bugpatterns."Bugpatternsarepoor

codingpracticesthataregenerallyincorrectandmayleadto

applicationerrors.Forexample,inthefollowingcode,ifthe

addressvariableisnull,thesecondlinewillgeneratea

NullPointerException:

Addressaddress=client.getAddress();

if((address!=null)||(address.getPostCode()!=null)){

...

}



Anotherexampleisshownhere,inwhichtheitemsmember

variableisaccessedwithouthavingbeeninitialized:

publicclassShoppingCart{

privateListitems;

publicaddItem(Itemitem){

items.add(item);

}

}



Errorsliketheseareofteneasytoidentifysimplybyreadingthe

code.However,althougheffective,codereviewsarelaborintensiveandtime-consuming,andwhereverpossibleitis

easiertoletthemachinedotheinspectionforyou!FindBugsis

designedtodojustthat.

FindBugsusestheApacheBCELlibrarytoanalyzetheclassesin

yourapplicationanddetectpotentialbugs.FindBugsrules(or

"detectors")useavarietyofinspectiontechniques,from

examiningthestructureoftheclassrightthroughtostudying

thedetaileddataflowthroughtheclass.Inadditiontothe

detectorsprovidedbyFindBugs,withabitofwork,youcan



writeyourowncustom-builtdetectors.

FindBugscomeswithover200rulesdividedintodifferent

categories:



Correctness



Theseissuesinvolvecodethatisprobablyincorrect

insomeway,forexample,codethatinvolvesan

infiniterecursivelooporthatreadsafieldthatis

neverwritten.Issuesinthiscategoryarealmost

certainlybugs.



Badpractice



AccordingtotheFindBugsteam,issuesinthis

categoryinvolve"clearviolationofrecommended

andstandardcodingpractice."Thebadpractices

thatFindBugsisinterestedingenerallyhavea

directcorrelationwithpotentialdefects,for

example,codethatdropsexceptionsorfailstoclose

fileordatabaseresources.Someoftheseissuesare

alsodetectedbyPMD.



Performance



Theseissuesaimatdetectingpotentialperformance

issues,suchascodeinvolvingunnecessaryobject

creation,orusingstringconcatenationinaloop

ratherthanusingaStringBuffer.



Multithreadedcorrectness



Theseisaspecialcategoryofissuesinvolving

problemswithsynchronizedandmultithreaded

code.



Dodgy



Thistypeofissueinvolvescodewhichseemsodd,

or"smellsbad,"inXPterminology,suchasunused

localvariablesoruncheckedcasts.Accordingtothe

FindBugsteam,lessthanhalfoftheseissues

involveactualbugs.

FindBugscanbeusedinthreeways;asastandaloneSwing

application,inEclipseusingtheEclipseplug-in,orintegrated

intothebuildprocessasanAnttaskorMavenreport.In

practice,thestandaloneapplicationisrarelyused:developers

prefertobeabletoinvokeFindBugsdirectlyfromwithintheir

workenvironment,whereasprojectmanagersandquality

assurancepeopleappreciatebeingabletodisplayproject-wide

bugreportsusingthereportingfeatures.

Intherestofthischapter,wewilllookathowtouseFindBugs

inthesedifferentcontexts.



23.2.UsingFindBugsinEclipse

FindBugscomeswithanEclipseplug-inthatprovidesexcellent

integrationwiththisIDE.UsingFindBugsfromwithinEclipse

hasobviousadvantagesforadeveloper:potentiallydangerous

bugscanbeidentifiedandfixedevenbeforecodeiscommitted

totherepository,whichallowsforamuchtighterdevelopment

cycle.



23.2.1.InstallingtheFindBugsPlug-In

TheeasiestwaytoinstalltheFindBugsEclipseplug-inistouse

theEclipseUpdatesite.Youdothisintheusualway:

1. OpentheHelp



SoftwareUpdates



FindandInstallmenu.



2. ClickNext,andchooseNewRemoteSite.

3. EntertheURLoftheremotesite

(http://findbugs.cs.umd.edu/eclipse/)andanappropriate

namesuchas"FindBugs."

4. MakesureyouhavetheFindBugssitecheckedinthe"Sites

toincludeinsearch"window,andclickFinish.Thenjustgo

throughtheinstallationscreenstoinstalltheplug-in.

Alternatively,youcandownloaditfromtheplug-indownload

site[80]andunzipthefileintoyourEclipseplug-indirectory.

[80]http://findbugs.sourceforge.net/downloads.html



Onceyouhaveinstalledtheplug-in,youneedtoactivate

FindBugsforyourproject.Opentheprojectpropertieswindow

(Project Properties).YouwillnowhaveaFindBugsentry(see

Figure23-1).ThiswindowallowsyoutoconfigureFindBugsin

detailforyourparticularprojectbyselectingwhichrulesyou

wanttoapply.Ifyoucheckthe"RunFindBugsautomatically"

checkbox,FindBugswillcheckforissueseverytimeyoumodify

aclass.



Figure23-1.ConfiguringFindBugsforaproject



Youcanalsofilterthetypesofissuesyouwantreported,either

bypriorityorbycategory.Forexample,ifyouwanttoignoreall

lowpriorityissues,justsettheminimumpriorityto"Medium"

(thisistherecommendedlevel).

NotethatsomeFindBugsissuesarequiteslow,suchas

FindTwoLockWait,FindNullDeref,FindOpenStream,

FindInconsistentSync2,andFindSleepWithLockHeld.Onlarger

projects,youmaywanttodisabletheserulesinthe

developmentenvironmentsandleavethissortofdetectionto

thecontinuousintegrationenvironment.



23.2.2.DetectingandDisplayingErrors

TheFindBugsEclipseplug-inisasimple,lightweighttoolwith

fewbellsandwhistles.IfyouhaveconfiguredFindBugstorun

automatically,itwillcheckforbugseverytimeyoumodifya

class.YoucanalsorunFindBugsusingthe"FindBugs"entryin

thecontextualmenu.Forlargeprojects,thiscantakeawhile.

ThesimplestwaytoviewtheissuesraisedbyFindBugsisinthe

Problemsview,wheretheyarelistedwithothererrorsand

warnings(seeFigure23-2).FindBugissuesarealsoindicatedin



thesourcecodebyadedicatedicon(aneasilyrecognizablered

bug).Ifyouneedmoredetails,clickonthebugiconinthe

marginorselectthe"ShowBugDetails"entryinthecontextual

menu;thiswilldisplaythe"BugDetails"view,whichcontainsa

moredetaileddescriptionoftheissue.

Figure23-2.FindBugissuesarelistedintheProblems

view



OnethingtorememberaboutFindBugsisthatitworkson

compiledbytecode,notonJavasourcefiles.So,ifyourproject

isnotconfiguredtobuildautomaticallyaftereachmodification

(Project BuildAutomatically),youwon'tseeanychangesin

theerrorsdisplayedbyFindBugsuntilyourecompilemanually.



23.3.SelectivelySuppressingRuleswith

FindBugFilters

LikeCheckstyle(seeSection21.7),FindBugsletsyoudefine

rulesindicatingwhichrulesshouldbeusedorexcludedin

particularcases,suchasinaparticularclassormethod.A

FindBugsfilterworksbycombiningoneormorefilterclauses,

suchasClass,BugCode,Method,andPriority.Matchingcases

maybeincludedorignored,dependingonhowthefilterfileis

used.Inmostcases,youuseafilterfiletoignorespecific

issues.

Let'slookatsomeexamples.ThefollowingfilterwillmatchDE

(methodmightdropexception)andEI(methodmayexpose

internalrepresentation)inthe

com.mycompany.example.MyClassclass:













Moreprecisely,wecangodowntothemethodlevel.The

followingfilterwillmatchtheseissues,butonlyinthe

processData()method:

















Or,ifthereareseveralmethodsthatneedtomatch,youcan



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 23. Preemptive Error Detection with FindBugs

Tải bản đầy đủ ngay(0 tr)

×