CodeComplete,SecondEdition
BySteveMcConnell
...............................................
Publisher:MicrosoftPress
PubDate:June09,2004
PrintISBN:0-7356-1967-0
Pages:960
TableofContents|Index
Takeastrategicapproachtosoftwareconstructionandproducesuperiorproductswiththisfully
updatededitionofSteveMcConnell'scriticallypraisedandaward-winningguidetosoftware
developmentbestpractices.
CodeComplete,SecondEdition
BySteveMcConnell
...............................................
Publisher:MicrosoftPress
PubDate:June09,2004
PrintISBN:0-7356-1967-0
Pages:960
TableofContents|Index
Copyright
Preface
WhoShouldReadThisBook?
WhereElseCanYouFindThisInformation?
KeyBenefitsofThisHandbook
WhyThisHandbookWasWritten
AuthorNote
Acknowledgments
AbouttheAuthor
SteveMcConnell
PartI:LayingtheFoundation
Inthispart:
Chapter1.WelcometoSoftwareConstruction
Section1.1.WhatIsSoftwareConstruction?
Section1.2.WhyIsSoftwareConstructionImportant?
Section1.3.HowtoReadThisBook
KeyPoints
Chapter2.MetaphorsforaRicherUnderstandingofSoftwareDevelopment
Section2.1.TheImportanceofMetaphors
Section2.2.HowtoUseSoftwareMetaphors
Section2.3.CommonSoftwareMetaphors
KeyPoints
Chapter3.MeasureTwice,CutOnce:UpstreamPrerequisites
Section3.1.ImportanceofPrerequisites
Section3.2.DeterminetheKindofSoftwareYou'reWorkingOn
Section3.3.Problem-DefinitionPrerequisite
Section3.4.RequirementsPrerequisite
Section3.5.ArchitecturePrerequisite
Section3.6.AmountofTimetoSpendonUpstreamPrerequisites
AdditionalResources
KeyPoints
Chapter4.KeyConstructionDecisions
Section4.1.ChoiceofProgrammingLanguage
Section4.2.ProgrammingConventions
Section4.3.YourLocationontheTechnologyWave
Section4.4.SelectionofMajorConstructionPractices
KeyPoints
PartII:CreatingHigh-QualityCode
Inthispart:
Chapter5.DesigninConstruction
Section5.1.DesignChallenges
Section5.2.KeyDesignConcepts
Section5.3.DesignBuildingBlocks:Heuristics
Section5.4.DesignPractices
Section5.5.CommentsonPopularMethodologies
AdditionalResources
KeyPoints
Chapter6.WorkingClasses
Section6.1.ClassFoundations:AbstractDataTypes(ADTs)
Section6.2.GoodClassInterfaces
Section6.3.DesignandImplementationIssues
Section6.4.ReasonstoCreateaClass
Section6.5.Language-SpecificIssues
Section6.6.BeyondClasses:Packages
AdditionalResources
KeyPoints
Chapter7.High-QualityRoutines
Section7.1.ValidReasonstoCreateaRoutine
Section7.2.DesignattheRoutineLevel
Section7.3.GoodRoutineNames
Section7.4.HowLongCanaRoutineBe?
Section7.5.HowtoUseRoutineParameters
Section7.6.SpecialConsiderationsintheUseofFunctions
Section7.7.MacroRoutinesandInlineRoutines
KeyPoints
Chapter8.DefensiveProgramming
Section8.1.ProtectingYourProgramfromInvalidInputs
Section8.2.Assertions
Section8.3.Error-HandlingTechniques
Section8.4.Exceptions
Section8.5.BarricadeYourProgramtoContaintheDamageCausedbyErrors
Section8.6.DebuggingAids
Section8.7.DeterminingHowMuchDefensiveProgrammingtoLeaveinProduction
Code
Section8.8.BeingDefensiveAboutDefensiveProgramming
AdditionalResources
KeyPoints
Chapter9.ThePseudocodeProgrammingProcess
Section9.1.SummaryofStepsinBuildingClassesandRoutines
Section9.2.PseudocodeforPros
Section9.3.ConstructingRoutinesbyUsingthePPP
Section9.4.AlternativestothePPP
KeyPoints
PartIII:Variables
Inthispart:
Chapter10.GeneralIssuesinUsingVariables
Section10.1.DataLiteracy
Section10.2.MakingVariableDeclarationsEasy
Section10.3.GuidelinesforInitializingVariables
Section10.4.Scope
Section10.5.Persistence
Section10.6.BindingTime
Section10.7.RelationshipBetweenDataTypesandControlStructures
Section10.8.UsingEachVariableforExactlyOnePurpose
KeyPoints
Chapter11.ThePowerofVariableNames
Section11.1.ConsiderationsinChoosingGoodNames
Section11.2.NamingSpecificTypesofData
Section11.3.ThePowerofNamingConventions
Section11.4.InformalNamingConventions
Section11.5.StandardizedPrefixes
Section11.6.CreatingShortNamesThatAreReadable
Section11.7.KindsofNamestoAvoid
KeyPoints
Chapter12.FundamentalDataTypes
Section12.1.NumbersinGeneral
Section12.2.Integers
Section12.3.Floating-PointNumbers
Section12.4.CharactersandStrings
Section12.5.BooleanVariables
Section12.6.EnumeratedTypes
Section12.7.NamedConstants
Section12.8.Arrays
Section12.9.CreatingYourOwnTypes(TypeAliasing)
KeyPoints
Chapter13.UnusualDataTypes
Section13.1.Structures
Section13.2.Pointers
Section13.3.GlobalData
AdditionalResources
KeyPoints
PartIV:Statements
Inthispart:
Chapter14.OrganizingStraight-LineCode
Section14.1.StatementsThatMustBeinaSpecificOrder
Section14.2.StatementsWhoseOrderDoesn'tMatter
KeyPoints
Chapter15.UsingConditionals
Section15.1.ifStatements
Section15.2.caseStatements
KeyPoints
Chapter16.ControllingLoops
Section16.1.SelectingtheKindofLoop
Section16.2.ControllingtheLoop
Section16.3.CreatingLoopsEasilyFromtheInsideOut
Section16.4.CorrespondenceBetweenLoopsandArrays
KeyPoints
Chapter17.UnusualControlStructures
Section17.1.MultipleReturnsfromaRoutine
Section17.2.Recursion
Section17.3.goto
Section17.4.PerspectiveonUnusualControlStructures
AdditionalResources
KeyPoints
Chapter18.Table-DrivenMethods
Section18.1.GeneralConsiderationsinUsingTable-DrivenMethods
Section18.2.DirectAccessTables
Section18.3.IndexedAccessTables
Section18.4.Stair-StepAccessTables
Section18.5.OtherExamplesofTableLookups
KeyPoints
Chapter19.GeneralControlIssues
Section19.1.BooleanExpressions
Section19.2.CompoundStatements(Blocks)
Section19.3.NullStatements
Section19.4.TamingDangerouslyDeepNesting
Section19.5.AProgrammingFoundation:StructuredProgramming
Section19.6.ControlStructuresandComplexity
KeyPoints
PartV:CodeImprovements
Inthispart:
Chapter20.TheSoftware-QualityLandscape
Section20.1.CharacteristicsofSoftwareQuality
Section20.2.TechniquesforImprovingSoftwareQuality
Section20.3.RelativeEffectivenessofQualityTechniques
Section20.4.WhentoDoQualityAssurance
Section20.5.TheGeneralPrincipleofSoftwareQuality
AdditionalResources
KeyPoints
Chapter21.CollaborativeConstruction
Section21.1.OverviewofCollaborativeDevelopmentPractices
Section21.2.PairProgramming
Section21.3.FormalInspections
Section21.4.OtherKindsofCollaborativeDevelopmentPractices
ComparisonofCollaborativeConstructionTechniques
AdditionalResources
KeyPoints
Chapter22.DeveloperTesting
Section22.1.RoleofDeveloperTestinginSoftwareQuality
Section22.2.RecommendedApproachtoDeveloperTesting
Section22.3.BagofTestingTricks
Section22.4.TypicalErrors
Section22.5.Test-SupportTools
Section22.6.ImprovingYourTesting
Section22.7.KeepingTestRecords
AdditionalResources
KeyPoints
Chapter23.Debugging
Section23.1.OverviewofDebuggingIssues
Section23.2.FindingaDefect
Section23.3.FixingaDefect
Section23.4.PsychologicalConsiderationsinDebugging
Section23.5.DebuggingToolsObviousandNot-So-Obvious
AdditionalResources
KeyPoints
Chapter24.Refactoring
Section24.1.KindsofSoftwareEvolution
Section24.2.IntroductiontoRefactoring
Section24.3.SpecificRefactorings
Section24.4.RefactoringSafely
Section24.5.RefactoringStrategies
AdditionalResources
KeyPoints
Chapter25.Code-TuningStrategies
Section25.1.PerformanceOverview
Section25.2.IntroductiontoCodeTuning
Section25.3.KindsofFatandMolasses
Section25.4.Measurement
Section25.5.Iteration
Section25.6.SummaryoftheApproachtoCodeTuning
AdditionalResources
KeyPoints
Chapter26.Code-TuningTechniques
Section26.1.Logic
Section26.2.Loops
Section26.3.DataTransformations
Section26.4.Expressions
Section26.5.Routines
Section26.6.RecodinginaLow-LevelLanguage
Section26.7.TheMoreThingsChange,theMoreTheyStaytheSame
AdditionalResources
KeyPoints
PartVI:SystemConsiderations
Inthispart:
Chapter27.HowProgramSizeAffectsConstruction
Section27.1.CommunicationandSize
Section27.2.RangeofProjectSizes
Section27.3.EffectofProjectSizeonErrors
Section27.4.EffectofProjectSizeonProductivity
Section27.5.EffectofProjectSizeonDevelopmentActivities
AdditionalResources
KeyPoints
Chapter28.ManagingConstruction
Section28.1.EncouragingGoodCoding
Section28.2.ConfigurationManagement
Section28.3.EstimatingaConstructionSchedule
Section28.5.TreatingProgrammersasPeople
Section28.6.ManagingYourManager
KeyPoints
Chapter29.Integration
Section29.1.ImportanceoftheIntegrationApproach
Section29.2.IntegrationFrequencyPhasedorIncremental?
Section29.3.IncrementalIntegrationStrategies
Section29.4.DailyBuildandSmokeTest
AdditionalResources
KeyPoints
Chapter30.ProgrammingTools
Section30.1.DesignTools
Section30.2.Source-CodeTools
Section30.3.Executable-CodeTools
Section30.4.Tool-OrientedEnvironments
Section30.5.BuildingYourOwnProgrammingTools
Section30.6.ToolFantasyland
AdditionalResources
KeyPoints
PartVII:SoftwareCraftsmanship
Inthispart:
Chapter31.LayoutandStyle
Section31.1.LayoutFundamentals
Section31.2.LayoutTechniques
Section31.3.LayoutStyles
Section31.4.LayingOutControlStructures
Section31.5.LayingOutIndividualStatements
Section31.6.LayingOutComments
Section31.7.LayingOutRoutines
Section31.8.LayingOutClasses
AdditionalResources
KeyPoints
Chapter32.Self-DocumentingCode
Section32.1.ExternalDocumentation
Section32.2.ProgrammingStyleasDocumentation
Section32.3.ToCommentorNottoComment
Section32.4.KeystoEffectiveComments
Section32.5.CommentingTechniques
Section32.6.IEEEStandards
AdditionalResources
KeyPoints
Chapter33.PersonalCharacter
Section33.1.Isn'tPersonalCharacterOfftheTopic?
Section33.2.IntelligenceandHumility
Section33.3.Curiosity
Section33.4.IntellectualHonesty
Section33.5.CommunicationandCooperation
Section33.6.CreativityandDiscipline
Section33.7.Laziness
Section33.8.CharacteristicsThatDon'tMatterAsMuchAsYouMightThink
Section33.9.Habits
AdditionalResources
KeyPoints
Chapter34.ThemesinSoftwareCraftsmanship
Section34.1.ConquerComplexity
Section34.2.PickYourProcess
Section34.3.WriteProgramsforPeopleFirst,ComputersSecond
Section34.4.ProgramintoYourLanguage,NotinIt
Section34.5.FocusYourAttentionwiththeHelpofConventions
Section34.6.PrograminTermsoftheProblemDomain
Section34.7.WatchforFallingRocks
Section34.8.Iterate,Repeatedly,AgainandAgain
Section34.9.ThouShaltRendSoftwareandReligionAsunder
KeyPoints
Chapter35.WheretoFindMoreInformation
Section35.1.InformationAboutSoftwareConstruction
Section35.2.TopicsBeyondConstruction
Section35.3.Periodicals
Section35.4.ASoftwareDeveloper'sReadingPlan
Section35.5.JoiningaProfessionalOrganization
Bibliography
Index
Copyright
PUBLISHEDBY
MicrosoftPress
ADivisionofMicrosoftCorporation
OneMicrosoftWay
Redmond,Washington98052-6399
Copyright©2004byStevenC.McConnell
Allrightsreserved.Nopartofthecontentsofthisbookmaybereproducedor
transmittedinanyformorbyanymeanswithoutthewrittenpermissionofthe
publisher.
LibraryofCongressCataloging-in-PublicationDataMcConnell,Steve
CodeComplete/SteveMcConnell.2nded.
p.cm.
Includesindex.
1.ComputerSoftwareDevelopmentHandbooks,manuals,etc.I.Title.
QA76.76.D47M392004
005.1dc222004049981
123456789QWT876543
DistributedinCanadabyH.B.FennandCompanyLtd.ACIPcataloguerecord
forthisbookisavailablefromtheBritishLibrary.
MicrosoftPressbooksareavailablethroughbooksellersanddistributors
worldwide.Forfurtherinformationaboutinternationaleditions,contactyour
localMicrosoftCorporationofficeorcontactMicrosoftPressInternational
directlyatfax(425)936-7329.VisitourWebsiteat
Sendcommentsto
Microsoft,MicrosoftPress,PowerPoint,VisualBasic,Windows,andWindows
NTareeitherregisteredtrademarksortrademarksofMicrosoftCorporationin
theUnitedStatesand/orothercountries.Otherproductandcompanynames
mentionedhereinmaybethetrademarksoftheirrespectiveowners.
Theexamplecompanies,organizations,products,domainnames,e-mail
addresses,logos,people,places,andeventsdepictedhereinarefictitious.No
associationwithanyrealcompany,organization,product,domainname,e-mail
address,logo,person,place,oreventisintendedorshouldbeinferred.
Thisbookexpressestheauthor'sviewsandopinions.Theinformationcontained
inthisbookisprovidedwithoutanyexpress,statutory,orimpliedwarranties.
Neithertheauthors,MicrosoftCorporation,noritsresellers,ordistributorswill
beheldliableforanydamagescausedorallegedtobecausedeitherdirectlyor
indirectlybythisbook.
AcquisitionsEditors:LindaEngelmanandRobinVanSteenburgh
ProjectEditor:DevonMusgrave
Indexer:BillMyers
PrincipalDesktopPublisher:CarlDiltz
BodyPartNo.X10-53130
Dedication
Tomywife,Ashlie,whodoesn'thavemuchtodowithcomputerprogramming
butwhohaseverythingtodowithenrichingtherestofmylifeinmoreways
thanIcouldpossiblydescribe
Preface
Thegapbetweenthebestsoftwareengineeringpracticeandtheaverage
practiceisverywideperhapswiderthaninanyotherengineering
discipline.Atoolthatdisseminatesgoodpracticewouldbeimportant.
FredBrooks
Myprimaryconcerninwritingthisbookhasbeentonarrowthegapbetweenthe
knowledgeofindustrygurusandprofessorsontheonehandandcommon
commercialpracticeontheother.Manypowerfulprogrammingtechniqueshide
injournalsandacademicpapersforyearsbeforetricklingdowntothe
programmingpublic.
Althoughleading-edgesoftware-developmentpracticehasadvancedrapidlyin
recentyears,commonpracticehasn't.Manyprogramsarestillbuggy,late,and
overbudget,andmanyfailtosatisfytheneedsoftheirusers.Researchersinboth
thesoftwareindustryandacademicsettingshavediscoveredeffectivepractices
thateliminatemostoftheprogrammingproblemsthathavebeenprevalentsince
the1970s.Becausethesepracticesaren'toftenreportedoutsidethepagesof
highlyspecializedtechnicaljournals,however,mostprogrammingorganizations
aren'tyetusingthemtoday.Studieshavefoundthatittypicallytakes5to15
yearsormoreforaresearchdevelopmenttomakeitswayintocommercial
practice(RaghavanandChand1989,Rogers1995,Parnas1999).Thishandbook
shortcutstheprocess,makingkeydiscoveriesavailabletotheaverage
programmernow.
WhoShouldReadThisBook?
Theresearchandprogrammingexperiencecollectedinthishandbookwillhelp
youtocreatehigher-qualitysoftwareandtodoyourworkmorequicklyandwith
fewerproblems.Thisbookwillgiveyouinsightintowhyyou'vehadproblems
inthepastandwillshowyouhowtoavoidproblemsinthefuture.The
programmingpracticesdescribedherewillhelpyoukeepbigprojectsunder
controlandhelpyoumaintainandmodifysoftwaresuccessfullyasthedemands
ofyourprojectschange.
ExperiencedProgrammers
Thishandbookservesexperiencedprogrammerswhowantacomprehensive,
easy-to-useguidetosoftwaredevelopment.Becausethisbookfocuseson
construction,themostfamiliarpartofthesoftwarelifecycle,itmakespowerful
softwaredevelopmenttechniquesunderstandabletoself-taughtprogrammersas
wellastoprogrammerswithformaltraining.
TechnicalLeads
ManytechnicalleadshaveusedCodeCompletetoeducateless-experienced
programmersontheirteams.Youcanalsouseittofillyourownknowledge
gaps.Ifyou'reanexperiencedprogrammer,youmightnotagreewithallmy
conclusions(andIwouldbesurprisedifyoudid),butifyoureadthisbookand
thinkabouteachissue,onlyrarelywillsomeonebringupaconstructionissue
thatyouhaven'tpreviouslyconsidered.
Self-TaughtProgrammers
Ifyouhaven'thadmuchformaltraining,you'reingoodcompany.About50,000
newdevelopersentertheprofessioneachyear(BLS2004,Hecker2004),but
onlyabout35,000software-relateddegreesareawardedeachyear(NCES2002).
Fromthesefiguresit'sashorthoptotheconclusionthatmanyprogrammers
don'treceiveaformaleducationinsoftwaredevelopment.Self-taught
programmersarefoundintheemerginggroupofprofessionalsengineers,
accountants,scientists,teachers,andsmallbusinessownerswhoprogramaspart
oftheirjobsbutwhodonotnecessarilyviewthemselvesasprogrammers.
Regardlessoftheextentofyourprogrammingeducation,thishandbookcangive
youinsightintoeffectiveprogrammingpractices.
Students
Thecounterpointtotheprogrammerwithexperiencebutlittleformaltrainingis
thefreshcollegegraduate.Therecentgraduateisoftenrichintheoretical
knowledgebutpoorinthepracticalknow-howthatgoesintobuilding
productionprograms.Thepracticalloreofgoodcodingisoftenpasseddown
slowlyintheritualistictribaldancesofsoftwarearchitects,projectleads,
analysts,andmore-experiencedprogrammers.Evenmoreoften,it'stheproduct
oftheindividualprogrammer'strialsanderrors.Thisbookisanalternativetothe
slowworkingsofthetraditionalintellectualpotlatch.Itpullstogetherthehelpful
tipsandeffectivedevelopmentstrategiespreviouslyavailablemainlybyhunting
andgatheringfromotherpeople'sexperience.It'sahandupforthestudent
makingthetransitionfromanacademicenvironmenttoaprofessionalone.
WhereElseCanYouFindThisInformation?
Thisbooksynthesizesconstructiontechniquesfromavarietyofsources.In
additiontobeingwidelyscattered,muchoftheaccumulatedwisdomabout
constructionhasresidedoutsidewrittensourcesforyears(Hildebrand1989,
McConnell1997a).Thereisnothingmysteriousabouttheeffective,highpoweredprogrammingtechniquesusedbyexpertprogrammers.Intheday-todayrushofgrindingoutthelatestproject,however,fewexpertstakethetimeto
sharewhattheyhavelearned.Consequently,programmersmayhavedifficulty
findingagoodsourceofprogramminginformation.
Thetechniquesdescribedinthisbookfillthevoidafterintroductoryand
advancedprogrammingtexts.AfteryouhavereadIntroductiontoJava,
AdvancedJava,andAdvancedAdvancedJava,whatbookdoyoureadtolearn
moreaboutprogramming?YoucouldreadbooksaboutthedetailsofIntelor
Motorolahardware,MicrosoftWindowsorLinuxoperating-systemfunctions,or
anotherprogramminglanguageyoucan'tusealanguageorprograminan
environmentwithoutagoodreferencetosuchdetails.Butthisisoneofthefew
booksthatdiscussesprogrammingperse.Someofthemostbeneficial
programmingaidsarepracticesthatyoucanuseregardlessoftheenvironment
orlanguageyou'reworkingin.Otherbooksgenerallyneglectsuchpractices,
whichiswhythisbookconcentratesonthem.
Theinformationinthisbookisdistilledfrommanysources,asshownbelow.
Theonlyotherwaytoobtaintheinformationyou'llfindinthishandbookwould
betoplowthroughamountainofbooksandafewhundredtechnicaljournals
andthenaddasignificantamountofreal-worldexperience.Ifyou'vealready
doneallthat,youcanstillbenefitfromthisbook'scollectingtheinformationin
oneplaceforeasyreference.
[Viewfullsizeimage]
KeyBenefitsofThisHandbook
Whateveryourbackground,thishandbookcanhelpyouwritebetterprogramsin
lesstimeandwithfewerheadaches.
Completesoftware-constructionreferenceThishandbookdiscussesgeneral
aspectsofconstructionsuchassoftwarequalityandwaystothinkabout
programming.Itgetsintonitty-grittyconstructiondetailssuchasstepsin
buildingclasses,insandoutsofusingdataandcontrolstructures,debugging,
refactoring,andcode-tuningtechniquesandstrategies.Youdon'tneedtoreadit
covertocovertolearnaboutthesetopics.Thebookisdesignedtomakeiteasy
tofindthespecificinformationthatinterestsyou.
Ready-to-usechecklistsThisbookincludesdozensofchecklistsyoucanuseto
assessyoursoftwarearchitecture,designapproach,classandroutinequality,
variablenames,controlstructures,layout,testcases,andmuchmore.
State-of-the-artinformationThishandbookdescribessomeofthemostup-todatetechniquesavailable,manyofwhichhavenotyetmadeitintocommonuse.
Becausethisbookdrawsfrombothpracticeandresearch,thetechniquesit
describeswillremainusefulforyears.
LargerperspectiveonsoftwaredevelopmentThisbookwillgiveyouachance
toriseabovethefrayofday-to-dayfirefightingandfigureoutwhatworksand
whatdoesn't.Fewpracticingprogrammershavethetimetoreadthroughthe
hundredsofbooksandjournalarticlesthathavebeendistilledintothis
handbook.Theresearchandrealworldexperiencegatheredintothishandbook
willinformandstimulateyourthinkingaboutyourprojects,enablingyoutotake
strategicactionsothatyoudon'thavetofightthesamebattlesagainandagain.
AbsenceofhypeSomesoftwarebookscontain1gramofinsightswathedin10
gramsofhype.Thisbookpresentsbalanceddiscussionsofeachtechnique's
strengthsandweaknesses.Youknowthedemandsofyourparticularproject
betterthananyoneelse.Thisbookprovidestheobjectiveinformationyouneed
tomakegooddecisionsaboutyourspecificcircumstances.
ConceptsapplicabletomostcommonlanguagesThisbookdescribes
techniquesyoucanusetogetthemostoutofwhateverlanguageyou'reusing,
whetherit'sC++,C#,Java,MicrosoftVisualBasic,orothersimilarlanguages.
NumerouscodeexamplesThebookcontainsalmost500examplesofgoodand
badcode.I'veincludedsomanyexamplesbecause,personally,Ilearnbestfrom
examples.Ithinkotherprogrammerslearnbestthatwaytoo.
Theexamplesareinmultiplelanguagesbecausemasteringmorethanone
languageisoftenawatershedinthecareerofaprofessionalprogrammer.Oncea
programmerrealizesthatprogrammingprinciplestranscendthesyntaxofany
specificlanguage,thedoorsswingopentoknowledgethattrulymakesa
differenceinqualityandproductivity.
Tomakethemultiple-languageburdenaslightaspossible,I'veavoidedesoteric
languagefeaturesexceptwherethey'respecificallydiscussed.Youdon'tneedto
understandeverynuanceofthecodefragmentstounderstandthepointsthey're
making.Ifyoufocusonthepointbeingillustrated,you'llfindthatyoucanread
thecoderegardlessofthelanguage.I'vetriedtomakeyourjobeveneasierby
annotatingthesignificantpartsoftheexamples.
AccesstoothersourcesofinformationThisbookcollectsmuchofthe
availableinformationonsoftwareconstruction,butit'shardlythelastword.
Throughoutthechapters,"AdditionalResources"sectionsdescribeotherbooks
andarticlesyoucanreadasyoupursuethetopicsyoufindmostinteresting.
BookwebsiteUpdatedchecklists,books,magazinearticles,Weblinks,and
othercontentareprovidedonacompanionwebsiteatcc2e.com.Toaccess
informationrelatedtoCodeComplete,2ded.,entercc2e.com/followedbya
four-digitcode,anexampleofwhichisshownhereintheleftmargin.These
websitereferencesappearthroughoutthebook.
WhyThisHandbookWasWritten
Theneedfordevelopmenthandbooksthatcaptureknowledgeabouteffective
developmentpracticesiswellrecognizedinthesoftware-engineering
community.AreportoftheComputerScienceandTechnologyBoardstatedthat
thebiggestgainsinsoftware-developmentqualityandproductivitywillcome
fromcodifying,unifying,anddistributingexistingknowledgeabouteffective
software-developmentpractices(CSTB1990,McConnell1997a).Theboard
concludedthatthestrategyforspreadingthatknowledgeshouldbebuiltonthe
conceptofsoftware-engineeringhandbooks.
TheTopicofConstructionHasBeenNeglected
Atonetime,softwaredevelopmentandcodingwerethoughttobeoneandthe
same.Butasdistinctactivitiesinthesoftware-developmentlifecyclehavebeen
identified,someofthebestmindsinthefieldhavespenttheirtimeanalyzing
anddebatingmethodsofprojectmanagement,requirements,design,andtesting.
Therushtostudythesenewlyidentifiedareashasleftcodeconstructionasthe
ignorantcousinofsoftwaredevelopment.
Discussionsaboutconstructionhavealsobeenhobbledbythesuggestionthat
treatingconstructionasadistinctsoftwaredevelopmentactivityimpliesthat
constructionmustalsobetreatedasadistinctphase.Inreality,software
activitiesandphasesdon'thavetobesetupinanyparticularrelationshiptoeach
other,andit'susefultodiscusstheactivityofconstructionregardlessofwhether
othersoftwareactivitiesareperformedinphases,initerations,orinsomeother
way.
ConstructionIsImportant
Anotherreasonconstructionhasbeenneglectedbyresearchersandwritersisthe
mistakenideathat,comparedtoothersoftware-developmentactivities,
constructionisarelativelymechanicalprocessthatpresentslittleopportunityfor
improvement.Nothingcouldbefurtherfromthetruth.
Codeconstructiontypicallymakesupabout65percentoftheeffortonsmall
projectsand50percentonmediumprojects.Constructionaccountsforabout75
percentoftheerrorsonsmallprojectsand50to75percentonmediumandlarge
projects.Anyactivitythataccountsfor50to75percentoftheerrorspresentsa
clearopportunityforimprovement.(Chapter27containsmoredetailsonthese
statistics.)
Somecommentatorshavepointedoutthatalthoughconstructionerrorsaccount
forahighpercentageoftotalerrors,constructionerrorstendtobelessexpensive
tofixthanthosecausedbyrequirementsandarchitecture,thesuggestionbeing
thattheyarethereforelessimportant.Theclaimthatconstructionerrorscostless
tofixistruebutmisleadingbecausethecostofnotfixingthemcanbeincredibly
high.Researchershavefoundthatsmall-scalecodingerrorsaccountforsomeof
themostexpensivesoftwareerrorsofalltime,withcostsrunningintohundreds
ofmillionsofdollars(Weinberg1983,SEN1990).Aninexpensivecosttofix
obviouslydoesnotimplythatfixingthemshouldbealowpriority.
Theironyoftheshiftinfocusawayfromconstructionisthatconstructionisthe
onlyactivitythat'sguaranteedtobedone.Requirementscanbeassumedrather
thandeveloped;architecturecanbeshortchangedratherthandesigned;and
testingcanbeabbreviatedorskippedratherthanfullyplannedandexecuted.But
ifthere'sgoingtobeaprogram,therehastobeconstruction,andthatmakes
constructionauniquelyfruitfulareainwhichtoimprovedevelopmentpractices.
NoComparableBookIsAvailable
Inlightofconstruction'sobviousimportance,IwassurewhenIconceivedthis
bookthatsomeoneelsewouldalreadyhavewrittenabookoneffective
constructionpractices.Theneedforabookabouthowtoprogrameffectively
seemedobvious.ButIfoundthatonlyafewbookshadbeenwrittenabout
constructionandthenonlyonpartsofthetopic.Somehadbeenwritten15years
ormoreearlierandemployedrelativelyesotericlanguagessuchasALGOL,
PL/I,Ratfor,andSmalltalk.Somewerewrittenbyprofessorswhowerenot
workingonproductioncode.Theprofessorswroteabouttechniquesthatworked
forstudentprojects,buttheyoftenhadlittleideaofhowthetechniqueswould
playoutinfull-scaledevelopmentenvironments.Stillotherbookstrumpetedthe
authors'newestfavoritemethodologiesbutignoredthehugerepositoryof
maturepracticesthathaveproventheireffectivenessovertime.
Inshort,Icouldn'tfindanybookthathadevenattemptedtocapturethebodyof
practicaltechniquesavailablefromprofessionalexperience,industryresearch,
andacademicwork.Thediscussionneededtobebroughtuptodateforcurrent
programminglanguages,object-orientedprogramming,andleading-edge
developmentpractices.Itseemedclearthatabookaboutprogrammingneededto
bewrittenbysomeonewhowasknowledgeableaboutthetheoreticalstateofthe
artbutwhowasalsobuildingenoughproductioncodetoappreciatethestateof
thepractice.Iconceivedthisbookasafulldiscussionofcodeconstructionfrom
oneprogrammertoanother.
WhenartcriticsgettogethertheytalkaboutFormandStructureand
Meaning.Whenartistsgettogethertheytalkaboutwhereyoucanbuy
cheapturpentine.
PabloPicasso
AuthorNote
Iwelcomeyourinquiriesaboutthetopicsdiscussedinthisbook,yourerror
reports,orotherrelatedsubjects.Pleasecontactmeat,
orvisitmywebsiteat.
Bellevue,Washington
MemorialDay,2004
MicrosoftLearningTechnicalSupport
Everyefforthasbeenmadetoensuretheaccuracyofthisbook.Microsoft
PressprovidescorrectionsforbooksthroughtheWorldWideWebatthe
followingaddress:
/>ToconnectdirectlytotheMicrosoftKnowledgeBaseandenteraquery
regardingaquestionorissuethatyoumayhave,goto:
/>Ifyouhavecomments,questions,orideasregardingthisbook,pleasesend
themtoMicrosoftPressusingeitherofthefollowingmethods:
PostalMail:
MicrosoftPress
Attn:CodeComplete2EEditor
OneMicrosoftWay
Redmond,WA98052-6399
E-mail:
Acknowledgments
Abookisneverreallywrittenbyoneperson(atleastnoneofmybooksare).A
secondeditionisevenmoreacollectiveundertaking.
I'dliketothankthepeoplewhocontributedreviewcommentsonsignificant
portionsofthebook:HákonÁgústsson,ScottAmbler,WillBarns,WilliamD.
Bartholomew,LarsBergstrom,IanBrockbank,BruceButler,JayCincotta,Alan
Cooper,BobCorrick,AlCorwin,JerryDeville,JonEaves,EdwardEstrada,
SteveGouldstone,OwainGriffiths,MatthewHarris,MichaelHoward,Andy
Hunt,KevinHutchison,RobJasper,StephenJenkins,RalphJohnsonandhis
SoftwareArchitectureGroupattheUniversityofIllinois,MarekKonopka,Jeff
Langr,AndyLester,MiticaManu,SteveMattingly,GarethMcCaughan,Robert
McGovern,ScottMeyers,GarethMorgan,MattPeloquin,BryanPflug,Jeffrey
Richter,SteveRinn,DougRosenberg,BrianSt.Pierre,DiomidisSpinellis,Matt
Stephens,DaveThomas,AndyThomas-Cramer,JohnVlissides,Pavel
Vozenilek,DennyWilliford,JackWoolley,andDeeZsombor.
Hundredsofreaderssentcommentsaboutthefirstedition,andmanymoresent
individualcommentsaboutthesecondedition.Thankstoeveryonewhotook
timetosharetheirreactionstothebookinitsvariousforms.
SpecialthankstotheConstruxSoftwarereviewerswhoformallyinspectedthe
entiremanuscript:JasonHills,BradeyHonsinger,AbdulNizar,TomReed,and
PamelaPerrott.Iwastrulyamazedathowthoroughtheirreviewwas,especially
consideringhowmanyeyeshadscrutinizedthebookbeforetheybeganworking
onit.ThanksalsotoBradey,Jason,andPamelafortheircontributionstothe
cc2e.comwebsite.
WorkingwithDevonMusgrave,projecteditorforthisbook,hasbeenaspecial
treat.I'veworkedwithnumerousexcellenteditorsonotherprojects,andDevon
standsoutasespeciallyconscientiousandeasytoworkwith.Thanks,Devon!
ThankstoLindaEnglemanwhochampionedthesecondedition;thisbook
wouldn'thavehappenedwithouther.ThanksalsototherestoftheMicrosoft
Pressstaff,includingRobinVanSteenburgh,EldenNelson,CarlDiltz,Joel
Panchot,PatriciaMasserman,BillMyers,SandiResnick,BarbaraNorfleet,
JamesKramer,andPrescottKlassen.
I'dliketoremembertheMicrosoftPressstaffthatpublishedthefirstedition:
AliceSmith,ArleneMyers,BarbaraRunyan,CarolLuke,ConnieLittle,Dean
Holmes,EricStroo,ErinO'Connor,JeannieMcGivern,JeffCarey,Jennifer
Harris,JenniferVick,JudithBloch,KatherineErickson,KimEggleston,Lisa
Sandburg,LisaTheobald,MargariteHargrave,MikeHalvorson,PatForgette,
PeggyHerman,RuthPettis,SallyBrunsman,ShawnPeck,SteveMurray,Wallis
Bolz,andZaafarHasnain.
Thankstothereviewerswhocontributedsosignificantlytothefirstedition:Al
Corwin,BillKiestler,BrianDaugherty,DaveMoore,GregHitchcock,Hank
Meuret,JackWoolley,JoeyWyrick,MargotPage,MikeKlein,Mike
Zevenbergen,PatForman,PeterPathe,RobertL.Glass,TammyForman,Tony
Pisculli,andWayneBeardsley.SpecialthankstoTonyGarlandforhis
exhaustivereview:with12years'hindsight,Iappreciatemorethaneverhow
exceptionalTony'sseveralthousandreviewcommentsreallywere.