关闭

关闭

关闭

封号提示

内容

首页 C++ Coding Standard.pdf

C++ Coding Standard.pdf

C++ Coding Standard.pdf

上传者: shenzhou1982 2011-06-28 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《C++ Coding Standardpdf》,可适用于高等教育领域,主题内容包含CCodingStandardCCodingStandardLastModified:tmhpossibilitycomMyHomePageUsin符等。

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/200
    暂无评论

精彩专题

上传我的资料

热门资料

资料评价:

/14
禁止下载

意见
反馈

返回
顶部

Q