关闭

关闭

关闭

封号提示

内容

首页 C++ Coding Standard

C++ Coding Standard.pdf

C++ Coding Standard

shenzhou1982
2011-06-28 0人阅读 0 0 0 暂无简介 举报

简介:本文档为《C++ Coding Standardpdf》,可适用于高等教育领域

CCodingStandardCCodingStandardLastModified:tmhpossibilitycomMyHomePageUsingthisStandardIfyouwanttomakealocalcopyofthisstandardanduseitasyourownyouareperfectlyfreetodosoThat'swhyImadeit!IfyoufindanyerrorsormakeanyimprovementspleaseemailmethechangessoIcanmergetheminRecentChangesContentslIntroductionmStandardizationisImportantmInterpretationmStandardsEnforcementmAcceptinganIdeamPhasesofaProject(joke)mFlowChartofProjectDecisionMaking(joke)mOnLeadershiplResourcesTakeaLook!mDesignStoriesmPatternsHomePagemOOInfoSourcesmUnifiedModelingLanguage(UML)mOPENMethodmOOFAQAllYouWantedtoKnowAboutOOmCFAQAllYouWantedtoKnowAboutCmCSourceLibrariesmCTutorialsmACECLibrarymCollectionofOtherStandardsmDesignbyContractfromEifflemCisn'tPerfect,HereareSomeReasonsWhymccdocisa'javadoc'likeutilitythatextractscommentsandrelevantinformationfromyourCCprogramsandgeneratesHTMLpagesfromitmConstCorrectnessAverynicearticleonconstcorrectnessbyChadLodermIntroductiontoCRCCardsAveryniceintrodctiontoCRCcardsmAbraxisCodeCheckAprogramforcheckingcodeforcodingstandardviolationsandotherproblemsfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardlNamesmMakeNamesFitmNoAllUpperCaseAbbreviationsmClassNamesmClassLibraryNamesmMethodNamesmClassAttributeNamesmMethodArgumentNamesmVariableNamesontheStackmPointerVariablesmReferenceVariablesandFunctionsReturningReferencesmGlobalVariablesmGlobalConstantsmStaticVariablesmTypeNamesmEnumNamesm#defineandMacroNamesmCFunctionNamesmCFileExtensionslDocumentationmCommentsonCommentsmCommentsShouldTellaStorymDocumentDecisionsmUseHeadersmMakeGotchasExplicitmInterfaceandImplementationDocumentationmDirectoryDocumentationmIncludeStatementDocumentationmBlockCommentslComplexityManagementmLayeringmMinimizeDependencieswithAbstractBaseClassesmLiskov'sSubstitutionPrinicplemOpenClosedPrinciplemRegisterDispatchIdiommDelegationmFollowtheLawofDemetermDesignbyContractlClassesmNamingClassFilesmClassLayoutmOrderofpublicprotectedprivatemWhatshouldgoinpublicprotectedprivatefile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardmPrototypeSourceFilemUseofNamespacesmUseHeaderFileGuardsmRequiredMethodsforaClassmMethodLayoutmFormatingMethodswithMultipleArgumentsmDifferentAccessorStylesmInitIdiomforInitializingObjectsmInitializeallVariablesmMinimizeInlinesmDoNotdoRealWorkinObjectConstructorsmBeCarefulThrowingExceptionsinDestructorsmBeConstCorrectmDon'tOverUseOperatorsmThinvsFatClassInterfacesmShortMethodslProcessmUseaDesignNotationandProcessmUsingUseCasesmUnifiedModelingLanguagemOPENMethodmCodeReviewsmCreateaSourceCodeControlSystemEarlyandNotOftenmCreateaBugTrackingSystemEarlyandNotOftenmRCSKeyword,ChangeLog,andHistoryPolicymHonorResponsibilitiesmProcessAutomationmUsingCRCCardsbyNancyMWilkinsonlFormattingmBrace{}PolicymIndentationTabsSpacePolicymParens()withKeyWordsandFunctionsPolicymALineShouldNotExceedCharactersmIfThenElseFormattingmswitchFormattingmUseofgoto,continue,breakand:mOneStatementPerLinemAlignmentofDeclarationBlockslPopularMythsmPromiseofOOmYoucan'tuseOOandConEmbeddedSystemslMiscellaneousmNoMagicNumbersfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardmErrorReturnCheckPolicymToUseEnumsorNottoUseEnumsmMacrosmDoNotDefaultIfTesttoNonZeromTheBullofBooleanTypesmUsuallyAvoidEmbeddedAssignmentsmReusingYourHardWorkandtheHardWorkofOthersmUseStreamsmUse#iftoCommentOutCodeBlocksmUse#ifNot#ifdefmMixingCandCmAlignmentofClassMembersmMiscellaneousmNoDataDefinitionsinHeaderFileslPortabilitymUseTypedefsforTypesmAlignmentofClassMembersmMinimizeInlinesmCompilerDependentExceptionsmCompilerDependentRTTIIntroductionStandardizationisImportantIthelpsifthestandardannoyseveryoneinsomewaysoeveryonefeelstheyareonthesameplayingfieldTheproposalherehasevolvedovermanyprojects,manycompanies,andliterallyatotalofmanyweeksspentarguingItisnoparticularperson'sstyleandiscertainlyopentolocalamendmentsGoodPointsWhenaprojecttriestoadheretocommonstandardsafewgoodthingshappen:lprogrammerscangointoanycodeandfigureoutwhat'sgoingonlnewpeoplecangetuptospeedquicklylpeoplenewtoCaresparedtheneedtodevelopapersonalstyleanddefendittothedeathlpeoplenewtoCaresparedmakingthesamemistakesoverandoveragainlpeoplemakefewermistakesinconsistentenvironmentslprogrammershaveacommonenemy:)file:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardBadPointsNowthebad:lthestandardisusuallystupidbecauseitwasmadebysomeonewhodoesn'tunderstandClthestandardisusuallystupidbecauseit'snotwhatIdolstandardsreducecreativitylstandardsareunnecessaryaslongaspeopleareconsistentlstandardsenforcetoomuchstructurelpeopleignorestandardsanywayDiscussionTheexperienceofmanyprojectsleadstotheconclusionthatusingcodingstandardsmakestheprojectgosmootherArestandardsnecessaryforsuccessOfcoursenotButtheyhelp,andweneedallthehelpwecanget!Behonest,mostargumentsagainstaparticularstandardcomefromtheegoFewdecisionsinareasonablestandardreallycanbesaidtobetechnicallydeficient,justmattersoftasteSobeflexible,controltheegoabit,andrememberanyprojectisfundamentallyateameffortInterpretationConventionsTheuseoftheword"shall"inthisdocumentrequiresthatanyprojectusingthisdocumentmustcomplywiththestatedstandardTheuseoftheword"should"directsprojectsintailoringaprojectspecificstandard,inthattheprojectmustinclude,exclude,ortailortherequirement,asappropriateTheuseoftheword"may"issimilarto"should",inthatitdesignatesoptionalrequirementsTerminologyForthesakeofsimplicity,theuseoftheword"compiler"meanscompilerortranslator"CCodingStandard"referstothisdocumentwhereas"CANSIStandard"referstothestandardClanguagedefinitionStandardsEnforcementFirst,anyseriousconcernsaboutthestandardshouldbebroughtupandworkedoutwithinthegroupMaybethestandardisnotquiteappropriateforyoursituationItmayhaveoverlookedimportantissuesormaybesomeoneinpowervehementlydisagreeswithcertainissues:)file:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardInanycase,oncefinalizedhopefullypeoplewillplaytheadultandunderstandthatthisstandardisreasonable,andhasbeenfoundreasonablebymanyotherprogrammers,andthereforeisworthyofbeingfollowedevenwithpersonalreservationsFailingwillingcooperationitcanbemadearequirementthatthisstandardmustbefollowedtopassacodeinspectionFailingthattheonlysolutionisamassiveticklingpartyontheoffendingpartyAcceptinganIdeaIt'simpossibleMaybeit'spossible,butit'sweakanduninterestingItistrueandItoldyousoIthoughtofitfirstHowcoulditbeotherwiseIfyoucometoobjectswithanegativepreconceptionpleasekeepanopenmindYoumaystillconcludeobjectsarebunk,butthere'saroadyoumustfollowtoacceptsomethingdifferentAllowyourselftotravelitforawhilePhasesofaProjectEnthusiasmDisillusionmentPanicASearchfortheGuiltyThePunishmentoftheInnocentPraiseandHonorfortheNonParticipantsFlowChartforProjectDecisionMaking|START||VYESNO|DOESTHE|||DAMNTHING||V|WORK|VNO|DON'TFUCK||DIDYOUFUCK||WITHIT||WITHIT|||file:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandard|||||YES||V|||||HIDE|NO|DOESANYONE|<|YOUDUMBSHIT!||||IT|<|KNOW||||||||||V|||||||YOUPOOR|YES|WILLYOU|||||BASTARD|<|CATCHHELL|<||||||||||NO||VV|V>|STOP|<|SHITCANIT|LeadershipIwishihadsaidthis,butitwassaidbyasdasdcomincompsoftwareengLeaders:leadbyexampledon'taskanythingofanyonetheywouldn'tdothemselvesarecalledontomakedifficultandunpopulardecisionskeeptheteamfocusedrewardsupporttheirteaminwhatevertheydokeepclearunnecessarycrapoutofthewayoftheteamConsensusisgreatIfitlastsfortheprojectlifecycle,consideryourselfblessedI'vebeenonacoupleprojectswheretwoengineersjustblantantly*disagreed*!#"x="#"x!="That'swhenaProjectLeaderisrequiredUnlessyouwanttoflipacoinOhyeaonemorethingProjectleaders:TAKEtheblamewhenthingsgowrongandSHAREthecreditwhenthingsgorightfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardAin'teasybutit'sthewayItrytorunmylifeNamesMakeNamesFitNamesaretheheartofprogrammingInthepastpeoplebelievedknowingsomeone'struenamegavethemmagicalpoweroverthatpersonIfyoucanthinkupthetruenameforsomething,yougiveyourselfandthepeoplecomingafterpoweroverthecodeDon'tlaugh!AnameistheresultofalongdeepthoughtprocessabouttheecologyitlivesinOnlyaprogrammerwhounderstandsthesystemasawholecancreateanamethat"fits"withthesystemIfthenameisappropriateeverythingfitstogethernaturally,relationshipsareclear,meaningisderivable,andreasoningfromcommonhumanexpectationsworksasexpectedIfyoufindallyournamescouldbeThingandDoItthenyoushouldprobablyrevisityourdesignClassNameslNametheclassafterwhatitisIfyoucan'tthinkofwhatitisthatisaclueyouhavenotthoughtthroughthedesignwellenoughlCompoundnamesofoverthreewordsareaclueyourdesignmaybeconfusingvariousentitiesinyoursystemRevisityourdesignTryaCRCcardsessiontoseeifyourobjectshavemoreresponsibilitiesthantheyshouldlAvoidthetemptationofbringingthenameoftheclassaclassderivesfromintothederivedclass'snameAclassshouldstandonitsownItdoesn'tmatterwhatitderivesfromlSuffixesaresometimeshelpfulForexample,ifyoursystemusesagentsthennamingsomethingDownloadAgentconveysrealinformationMethodandFunctionNameslUsuallyeverymethodandfunctionperformsanaction,sothenameshouldmakeclearwhatitdoes:CheckForErrors()insteadofErrorCheck(),DumpDataToFile()insteadofDataFile()ThiswillalsomakefunctionsanddataobjectsmoredistinguishablelSuffixesaresometimesuseful:mMaxtomeanthemaximumvaluesomethingcanhavemCntthecurrentcountofarunningcountvariablemKeykeyvalueForexample:RetryMaxtomeanthemaximumnumberofretries,RetryCnttomeanthecurrentretrycountlPrefixesaresometimesuseful:file:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardmIstoaskaquestionaboutsomethingWheneversomeoneseesIstheywillknowit'saquestionmGetgetavaluemSetsetavalueForexample:IsHitRetryLimitNoAllUpperCaseAbbreviationslWhenconfrontedwithasituationwhereyoucoulduseanalluppercaseabbreviationinsteaduseaninitialuppercaseletterfollowedbyalllowercaselettersNomatterwhatJustificationlPeopleseemtohaveverydifferentintuitionswhenmakingnamescontainingabbreviationsIt'sbesttosettleononestrategysothenamesareabsolutelypredictableTakeforexampleNetworkABCKeyNoticehowtheCfromABCandKfromkeyareconfusedSomepeopledon'tmindthisandothersjusthateitsoyou'llfinddifferentpoliciesindifferentcodesoyouneverknowwhattocallsomethingExampleclassFluidOzNOTFluidOZclassNetworkAbcKeyNOTNetworkABCKeyClassNameslUseuppercaselettersaswordseparators,lowercasefortherestofawordlFirstcharacterinanameisuppercaselNounderbars('')JustificationlOfallthedifferentnamingstrategiesmanypeoplefoundthisonethebestcompromiseExampleclassNameOneTwoclassNamefile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardClassLibraryNameslNowthatnamespacesarebecomingmorewidelyimplemented,namespacesshouldbeusedtopreventclassnameconflictsamonglibrariesfromdifferentvendorsandgroupslWhennotusingnamespaces,it'scommontopreventclassnameclashesbyprefixingclassnameswithauniquestringTwocharactersissufficient,butalongerlengthisfineExampleJohnJohnson'scompletedatastructurelibrarycoulduseJJasaprefix,soclasseswouldbe:classJjLinkList{}MethodNameslUsethesameruleasforclassnamesJustificationlOfallthedifferentnamingstrategiesmanypeoplefoundthisonethebestcompromiseExampleclassNameOneTwo{public:intDoIt()voidHandleError()}ClassAttributeNameslAttributenamesshouldbeprependedwiththecharacter'm'lAfterthe'm'usethesamerulesasforclassnamesl'm'alwaysprecedesothernamemodifierslike'p'forpointerfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardJustificationlPrepending'm'preventsanyconflictwithmethodnamesOftenyourmethodsandattributenameswillbesimilar,especiallyforaccessorsExampleclassNameOneTwo{public:intVarAbc()intErrorNumber()private:intmVarAbcintmErrorNumberString*mpName}MethodArgumentNameslThefirstcharactershouldbelowercaselAllwordbeginningsafterthefirstlettershouldbeuppercaseaswithclassnamesJustificationlYoucanalwaystellwhichvariablesarepassedinvariableslYoucanusenamessimilartoclassnameswithoutconflictingwithclassnamesExampleclassNameOneTwo{public:intStartYourEngines(EnginerSomeEngine,EnginerAnotherEngine)}VariableNamesontheStackfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardlusealllowercaselettersluse''asthewordseparatorJustificationlWiththisapproachthescopeofthevariableisclearinthecodelNowallvariableslookdifferentandareidentifiableinthecodeExampleintNameOneTwo::HandleError(interrorNumber){interror=OsErr()TimetimeoferrorErrorProcessorerrorprocessor}PointerVariableslpointersshouldbeprependedbya'p'inmostcaseslplacethe*closetothepointertypenotthevariablenameJustificationlTheideaisthatthedifferencebetweenapointer,object,andareferencetoanobjectisimportantforunderstandingthecode,especiallyinCwhere>canbeoverloaded,andcastingandcopysemanticsareimportantlPointersreallyareachangeoftypesothe*belongsnearthetypeOnereservationwiththispolicyrelatestodeclaringmultiplevariableswiththesametypeonthesamelineInCthepointermodifieronlyappliestotheclosestvariable,notallofthem,whichcanbeveryconfusing,especiallyfornewbiesYouwanttohaveonedeclarationperlineanywaysoyoucandocumenteachvariableExampleString*pName=newStringString*pName,name,addressnote,onlypNameisapointerReferenceVariablesandFunctionsReturningfile:E|ComputerProgramDesignCAndCCCodingStandardhtm(of):CCodingStandardReferenceslReferencesshouldbeprependedwith'r'JustificationlThedifferencebe

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

评分:

/14

1下载券

立即下载

扫码寻找文档

送下载券

加入VIP

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料