Tải bản đầy đủ - 0 (trang)
Chapter 19.  Always initialize variables

Chapter 19.  Always initialize variables

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

Summary

Startwithacleanslate:Uninitializedvariablesareacommon

sourceofbugsinCandC++programs.Avoidsuchbugsby

beingdisciplinedaboutcleaningmemorybeforeyouuseit;

initializevariablesupondefinition.



Discussion

Inthelow-levelefficiencytraditionofCandC++alike,the

compilerisoftennotrequiredtoinitializevariablesunlessyou

doitexplicitly(e.g.,localvariables,forgottenmembersomitted

fromconstructorinitializerlists).Doitexplicitly.

Therearefewreasonstoeverleaveavariableuninitialized.

Noneisseriousenoughtojustifythehazardofundefined

behavior.

Ifyou'veusedaprocedurallanguage(e.g.,Pascal,C,Fortran,

orCobol)youmightbeusedtodefiningvariablesinseparation

fromthecodethatusesthem,andthenassigningthemvalues

laterwhenthey'reabouttobeused.Thisapproachisobsolete

andnotrecommended(seeItem18).

Acommonmisconceptionaboutuninitializedvariablesisthat

theywillcrashtheprogram,sothatthosefewuninitialized

variableslyingaroundhereandtherewillbequicklyrevealed

bysimpletesting.Onthecontrary,programswithuninitialized

variablescanrunflawlesslyforyearsifthebitsinthememory

happentomatchtheprogram'sneeds.Later,acallfroma

differentcontext,arecompilation,orsomechangeinanother

partoftheprogramwillcausefailuresrangingfrominexplicable

behaviortointermittentcrashes.



Examples

Example1:Usingadefaultinitialvalueor?:toreducemixing

dataflowwithcontrolflow.

//Notrecommended:Doesn'tinitializevariable

intspeedupFactor;

if(condition)

speedupFactor=2;

else

speedupFactor=-1;

//Better:Initializesvariable

intspeedupFactor=-1;

if(condition)

speedupFactor=2;

//Better:Initializesvariable

intspeedupFactor=condition?2:-1;



Thebetteralternativesnicelyleavenogapbetweendefinition

andinitialization.

Example2:Replacingacomplicatedcomputationalflowwitha

function.Sometimesavalueiscomputedinawaythatisbest

encapsulatedinafunction(seeItem11):

//Notrecommended:Doesn'tinitializevariable

intspeedupFactor;

if(condition){

//code

speedupFactor=someValue;

}else{

//code



speedupFactor=someOtherValue;

}

//Better:Initializesvariable

intspeedupFactor=ComputeSpeedupFactor();



Example3:Initializingarrays.Forlargeaggregatetypessuch

asarrays,properinitializationdoesnotalwaysmeanhavingto

reallytouchallthedata.Forexample,sayyouuseanAPIthat

forcesyoutousefixedarraysofcharofsizeMAX_PATH(butsee

Items77and78).Ifyouaresurethearraysarealwaystreated

asnull-terminatedCstrings,thisimmediateassignmentisgood

enough:

//Acceptable:Createanemptypath

charpath[MAX_PATH];path[0]='\0';



Thefollowingsaferinitializationfillsallthecharactersinthe

arraywithzero:

//Better:Createazero-filledpath

charpath[MAX_PATH]={'\0'};



Bothvariantsabovearerecommended,butingeneralyou

shouldprefersafetytounneededefficiency.



Exceptions

Inputbuffersandvolatiledatathatisdirectlywrittenby

hardwareorotherprocessesdoesnotneedtobeinitializedby

theprogram.



References

[Dewhurst03]Đ48[Stroustrup00]Đ4.9.5,Đ6.3



20.Avoidlongfunctions.Avoiddeep

nesting

Summary

Discussion

Exceptions

References



Summary

Shortisbetterthanlong,flatisbetterthandeep:Excessively

longfunctionsandnestedcodeblocksareoftencausedby

failingtogiveonefunctiononecohesiveresponsibility(seeItem

5),andbothareusuallysolvedbybetterrefactoring.



Discussion

Everyfunctionshouldbeacoherentunitofworkbearinga

suggestivename(seeItem5andtheDiscussioninItem70).

Whenafunctioninsteadtriestomergesuchsmallconceptual

elementsinsidealongfunctionbody,itendsupdoingtoo

much.

Excessivestraight-linefunctionlengthandexcessiveblock

nestingdepth(e.g.,if,for,while,andtryblocks)aretwin

culpritsthatmakefunctionsmoredifficulttounderstandand

maintain,andoftenneedlesslyso.

Eachlevelofnestingaddsintellectualoverheadwhenreading

codebecauseyouneedtomaintainamentalstack(e.g.,enter

conditional,enterloop,enterTRy,enterconditional,).Have

youeverfoundaclosingbraceinsomeone'scodeand

wonderedwhichofthemanyfors,whiles,orifsitmatched?

Preferbetterfunctionaldecompositiontohelpavoidforcing

readerstokeepasmuchcontextinmindatatime.

Exercisecommonsenseandreasonableness:Limitthelength

anddepthofyourfunctions.Allofthefollowinggoodadvice

alsohelpsreducelengthandnesting:

Prefercohesion:Giveonefunctiononeresponsibility(see

Item5).

Don'trepeatyourself:Preferanamedfunctionover

repeatedsimilarcodesnippets.

Prefer&&:Avoidnestedconsecutiveifswherean&&

conditionwilldo.



Don'ttrytoohard:Preferautomaticcleanupvia

destructorsoverTRyblocks(seeItem13).

Preferalgorithms:They'reflatterthanloops,andoften

better(seeItem84).

Don'tswitchontypetags.Preferpolymorphicfunctions

(seeItem90).



Exceptions

Afunctionmightbelegitimatelylongand/ordeepwhenits

functionalitycan'tbereasonablyrefactoredintoindependent

subtasksbecauseeverypotentialrefactoringwouldrequire

passingmanylocalvariablesandcontext(renderingtheresult

lessreadableratherthanmorereadable).Butifseveralsuch

potentialfunctionstakesimilararguments,theymightbe

candidatesforbecomingmembersofanewclass.



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

Chapter 19.  Always initialize variables

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

×