关闭

关闭

关闭

封号提示

内容

首页 API Design for C++

API Design for C++.pdf

API Design for C++

tangwei19811102 2013-09-16 评分 0 浏览量 0 0 0 0 暂无简介 简介 举报

简介:本文档为《API Design for C++pdf》,可适用于IT/计算机领域,主题内容包含APIDesignforCAPIDesignforCMartinReddyAMSTERDAM•BOSTON•HEIDELBERG•LONDONNEW符等。

APIDesignforCAPIDesignforCMartinReddyAMSTERDAM•BOSTON•HEIDELBERG•LONDONNEWYORK•OXFORD•PARIS•SANDIEGOSANFRANCISCO•SINGAPORE•SYDNEY•TOKYOMorganKaufmannPublishersisanimprintofElsevierAcquiringEditor:ToddGreenNopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,oranyinformationstorageandretrievalsystem,withoutpermissioninwritingfromthepublisherDetailsonhowtoseekpermission,furtherinformationaboutthePublisher’spermissionspoliciesandourarrangementswithorganizationssuchastheCopyrightClearanceCenterandtheCopyrightLicensingAgency,canbefoundatourwebsite:wwwelseviercompermissionsThisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythePublisher(otherthanasmaybenotedherein)NoticesKnowledgeandbestpracticeinthisfieldareconstantlychangingAsnewresearchandexperiencebroadenourunderstanding,changesinresearchmethodsorprofessionalpracticesmaybecomenecessaryPractitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluatingandusinganyinformationormethodsdescribedhereinInusingsuchinformationormethodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,includingpartiesforwhomtheyhaveaprofessionalresponsibilityTothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assumeanyliabilityforanyinjuryandordamagetopersonsorpropertyasamatterofproductsliability,negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideascontainedinthematerialhereinLibraryofCongressCataloginginPublicationDataApplicationsubmittedBritishLibraryCataloguinginPublicationDataAcataloguerecordforthisbookisavailablefromtheBritishLibraryISBN:PrintedintheUnitedStatesofAmericaEditorialAssistant:RobynDayProjectManager:AndreCuelloDesigner:EricDeCiccoMorganKaufmannisanimprintofElsevierCorporateDrive,Suite,Burlington,MA,USA#Elsevier,IncAllrightsreservedForinformationonallMKpublicationsvisitourwebsiteatwwwmkpcomForewordIshouldbeginbyconfessingthatIdonotconsidermyselfaworldclassAPIdesignerorsoftwareengineerIdo,however,considermyselfanexpertresearcherintheareasofcomputergraphicsandgeometricmodelingItwasinthislineofworkthatIfirstmetMartinatPixarAnimationStudiosxvAsagraphicsresearcherIwasaccustomedtowritingmathematicallysophisticatedpapersIwasalsoformallytrainedasacomputerscientistatamajoruniversityandhadwrittenmyshareofcodeArmedwiththisbackground,whenIwaspresentedwiththeopportunitytoleadagroupofsoftwareengineersworkingonanewgenerationofanimationsoftwareforPixar,Ifiguredthatitcouldn’tbeanymoredifficultthanresearchAfterall,researchis,bydefinition,thecreationoftheunknown,whereasengineeringistheimplementationofwellunderstoodsubjectsIcouldnothavebeenmorewrongIcametorealizethatsoftwareengineeringwas,withoutadoubt,themostdifficultchallengeIhadeverbeenpresentedwithAftermoreyearsthanIcaretoadmit,IeventuallygaveupandwentbacktographicsresearchIcan’ttellyouhowmuchIwouldhavebenefittedfromabooksuchas“APIDesignforC”ManyofthelessonswelearnedthehardwayhavebeencapturedbyMartininthisinsightful,easytousebookMartinapproachesthesubjectnotfromtheperspectiveofanacademicsoftwareresearcher(althoughhedrawsheavilyfromresultsandinsightsgainedthere),butfromtheperspectiveofaninthetrenchessoftwareengineerandmanagerHehasexperiencedfirsthandtheimportanceofgoodsoftwaredesignandhasemergedasanarticulatevoiceofwhat“good”meansInthisbookhepresentseffectivestrategiesforachievingthatgoalIparticularlylikethatMartinisnotfocusingjustonAPIdesign,butmorebroadlyonsoftwarelifecycles,allowinghimtocovertopicssuchasversioning,strategiesforbackwardcompatibility,andbranchingmethodologiesInshort,thisbookshouldbeofgreatvaluetothosecreatingormanagingsoftwareactivitiesItisacomprehensivecollectionofbestpracticesthathaveproventhemselvestimeandtimeagainTonyDeRoseSeniorScientistandResearchGroupLead,PixarAnimationStudiosAnAPIpresentsalogicalinterfacetoasoftwarecomponentandhidestheinternaldetailsrequiredtoimplementthatcomponentItoffersahighlevelabstractionforamoduleandpromotesmorecostlytofixthanabuginyourimplementationForinstance,aninterfacechangemayrequirealloftheapplicationsbasedonyourcodetobeupdated,whereasanimplementacanbeintegratedtransparentlyandeffortlesslyintoclientapplicationswhenthetiononlychangeyadoptthenewxviicodereusebyallowingmultipleapplicationstosharethesamefunctionalityModernsoftwaredevelopmenthasbecomehighlydependentonAPIs,fromlowlevelapplicationframeworkstodataformatAPIsandgraphicaluserinterface(GUI)frameworksInfact,commonsoftwareengineeringtermssuchasmodulardevelopment,codereuse,componentization,dynamiclinklibraryorDLL,softwareframeworks,distributedcomputing,andserviceorientedarchitectureallimplytheneedforstrongAPIdesignskillsSomepopularCandCAPIsthatyoumayalreadybeawareofincludetheStandardTemplateLibrary(STL),Boost,theMicrosoftWindowsAPI(Win),MicrosoftFoundationClasses(MFC),libtiff,libpng,zlib,libxml,OpenGL,MySQL,Trolltech’sQt,wxWidgets,GTK,KDE,SkypeKit,POSIXpthreads,Intel’sThreadingBuildingBlocks,theNetscapePluginAPI,andtheApachemoduleAPIInaddition,manyofGoogle’sopensourceprojectsareC,asismuchofthecodeonthesourceforgenet,bitbucketorg,andfreshmeatnetWebsitesAPIssuchastheseareusedinallfacetsofsoftwaredevelopment,fromdesktopapplications,tomobilecomputingandembeddedsystems,toWebdevelopmentForexample,theMozillaFirefoxWebbrowserisbuiltontopofmorethandynamiclibraries,eachofwhichprovidestheimplementationforoneormoreAPIsElegantandrobustAPIdesignisthereforeacriticalaspectofcontemporarysoftwaredevelopmentOneimportantwayinwhichthisdiffersfromstandardapplicationdevelopmentisthefargreaterneedforchangemanagementAsweallknow,changeisaninevitablefactorinsoftwaredevelopmentnewrequirements,featurerequests,andbugfixescausesoftwaretoevolveinwaysthatwereneveranticipatedwhenitwasfirstdevisedHowever,changestoanAPIthatissharedbyhundredsofenduserapplicationscancausemajorupheavalandultimatelymaycauseclientstoabandonanAPITheprimarygoalofgoodAPIdesignisthereforetoprovideyourclientswiththefunctionalitytheyneedwhilealsocausingminimalimpacttotheircodeideallyzeroimpactwhenyoureleaseanewversionWHYYOUSHOULDREADTHISBOOKIfyouwriteCcodethatanotherengineerreliesupon,you’reanAPIdesignerandthisbookhasbeenwrittenforyouInterfacesarethemostimportantcodethatyouwritebecauseaproblemwithyourinterfaceisfarPrefaceWritinglargeapplicationsinCisacomplexandtrickybusinessHowever,designingreusableCinterfacesthatarerobust,stable,easytouse,anddurableisevenmoredifficultThebestwaytosucceedinthisendeavoristoadheretothetenetsofgoodApplicationProgrammingInterface(API)designimplementation,testing,documentation,release,versioning,maintenance,anddeprecationIwillxviiiPrefaceevencoverspecializedAPItopicssuchascreatingscriptingandpluginAPIsWhilemanyofthesetopicsarealsorelevanttosoftwaredevelopmentingeneral,thefocusherewillbeontheparticularimplicationsforAPIdesignForexample,whendiscussingtestingstrategiesIwillconcentrateonautomatedAPItestingtechniquesratherthanattemptingtoincludeenduserapplicationtestingtechniquessuchasGUItesting,systemtesting,ormanualtestingIntermsofmyowncredentialstowritethisbook,IhaveledthedevelopmentofAPIsforresearchcodesharedbyseveralcollaboratinginstitutions,inhouseanimationsystemAPIsthathavebeenusedtomakeAcademyAwardwinningmovies,andopensourceclientserverAPIsthathavebeenusedbymillionsofpeopleworldwideThroughoutallofthesedisparateexperiences,IhaveconsistentlywitnessedtheneedforhighqualityAPIdesignThisbookthereforepresentsapracticaldistillationofthetechniquesandstrategiesofindustrialstrengthAPIdesignthathavebeendrawnfromarangeofrealworldexperiencesWHOISTHETARGETAUDIENCEWhilethisbookisnotabeginner’sguidetoC,IhavemadeeveryefforttomakethetexteasytoreadandtoexplainallterminologyandjargonclearlyThebookshouldthereforebevaluabletonewprogrammerswhohavegraspedthefundamentalsofCandwanttoadvancetheirdesignskills,aswellasseniorengineersandsoftwarearchitectswhoareseekingtogainnewexpertisetocomplementtheirexistingtalentsTherearethreespecificgroupsofreadersthatIhaveborneinmindwhilewritingthisbookPracticingsoftwareengineersandarchitectsJuniorandseniordeveloperswhoareworkingonaspecificAPIprojectandneedpragmaticadviceonhowtoproducethemostelegantandenduringdesignTechnicalmanagersProgramandproductmanagerswhoareresponsibleforproducinganAPIproductandwhowanttogaingreaterinsightintothetechnicalissuesanddevelopmentprocessesofAPIdesignAPIversionPutinmoreeconomicterms,apoorlydesignedinterfacecanseriouslyreducethelongtermsurvivalofyourcodeLearninghowtocreatehighqualityinterfacesisthereforeanessentialengineeringskill,andthecentralfocusofthisbookAsMichiHenningnoted,APIdesignismoreimportanttodaythanitwasyearsagoThisisbecausemanymoreAPIshavebeendesignedinrecentyearsThesealsoprovidericherandmorecomplexfunctionalityandaresharedbymoreenduserapplications(Henning,)Despitethisfact,nootherbookscurrentlyonthemarketconcentrateonthetopicofAPIdesignforCIt’sworthnotingthatthisbookisnotmeanttobeageneralCprogrammingguidetherearealreadymanygoodexamplesoftheseonthemarketIwillcertainlycoverlotsofobjectorienteddesignmaterialandpresentmanyhandyCtipsandtricksHowever,IwillfocusontechniquesforrepresentingcleanmodularinterfacesinCBycorollary,Iwillnotdiveasdeeplyintothequestionofhowtoimplementthecodebehindtheseinterfaces,suchasspecificalgorithmchoicesorbestpracticeslimitedtothecodewithinthecurlybracesofyourfunctionbodiesHowever,thisbookwillcoverthefullbreadthofAPIdevelopment,frominitialdesignthroughxixPrefaceCONVENTIONSWhileitismoretraditionaltoemploytheterm“user”tomeanapersonwhousesasoftwareapplication,suchasauserofMicrosoftWordorMozillaFirefox,inthecontextofAPIdesignIwillapplythetermtomeanasoftwaredeveloperwhoiscreatinganapplicationandisusinganAPItoachieveFOCUSINGONCWhiletherearemanygenericAPIdesignmethodologiesthatcanbetaughtskillsthatapplyequallywelltoanyprogramminglanguageorenvironmentultimatelyanAPIhastobeexpressedinaparticularprogramminglanguageItisthereforeimportanttounderstandthelanguagespecificfeaturesthatcontributetoexemplaryAPIdesignThisbookisthereforefocusedontheissuesofdesigningAPIsforasinglelanguage(C)ratherthandilutingthecontenttomakeitapplicableforalllanguagesWhilereaderswhowishtodevelopAPIsforotherlanguages,suchasJavaorC#,maystillgainmuchgeneralinsightfromthistext,thebookisdirectlytargetedatCengineerswhomustwriteandmaintainAPIsforotherengineerstoconsumeCisstilloneofthemostwidelyusedprogramminglanguagesforlargesoftwareprojectsandtendstobethemostpopularchoiceforperformancecriticalcodeAsaresult,therearemanydiverseCandCAPIsavailableforyoutouseinyourownapplications(someofwhichIlistedearlier)IwillthereforeconcentrateonaspectsofproducinggoodAPIsinCandincludecopioussourcecodeexamplestoillustratetheseconceptsbetterThismeansthatIwilldealwithCspecifictopicssuchastemplates,encapsulation,inheritance,namespaces,operators,constcorrectness,memorymanagement,useofSTL,thepimplidiom,andsoonAdditionally,thisbookwillbepublishedduringanexcitingtimeintheevolutionofCAnewversionoftheCspecificationiscurrentlyworkingitswaythroughtheISOIECstandardizationprocessMostCcompilerscurrentlyaimtoconformtothestandardthatwasfirstpublishedin,knownasCAlaterrevisionofthisstandardwaspublishedintocorrectseveraldefectsSincethattime,thestandardscommitteehasbeenworkingonamajornewversionofthespecificationThisversionisreferredtoinformallyasCx,untilsuchtimethatthestandardisratifiedandthedateofpublicationisknownBythetimeyoureadthisbook,thenewstandardwilllikelyhavebeenpublishedHowever,atthetimeofwriting,itisstillreferredtoasCxNonetheless,Cxhasreachedanadvancedstageofthestandardizationprocess,andmanyofthenewfeaturescanbepredictedwithrelativelyhighconfidenceInfact,someofthemajorCcompilershavealreadystartedtoimplementmanyoftheproposednewfeaturesIntermsofAPIdesign,severalofthesenewlanguagefeaturescanbeusedtoproducemoreelegantandsturdyinterfacesAssuch,IhaveendeavoredtohighlightandexplainthoseareasofCxthroughoutthebookThisbookshouldthereforeremainarelevantresourceforseveralyearstocomeStudentsandeducatorsComputerscienceandsoftwareengineeringstudentswhoarelearninghowtoprogramandareseekingathoroughresourceonsoftwaredesignthatisinformedbypracticalexperienceonlargescaleprojectsxxPrefacethisInotherwords,IwillgenerallybetalkingaboutAPIusersandnotapplicationusersTheterm“client”willbeusedsynonymouslyinthisregardNotethattheterm“client,”inadditiontoreferringtoahumanuserofyourAPI,canalsoreferimpersonallytootherpiecesofsoftwarethatmustcallfunctionsinyourAPIWhiletherearemanyfileformatextensionsusedtoidentifyCsourceandheaderfiles,suchascpp,cc,cxx,h,hh,andhpp,Iwillstandardizeontheuseofcppandhthroughoutthisbook“Iwillalsousethetermsmoduleandcomponent”interchangeablytomeanasinglecppandhfilepairThesearenotablynotequivalenttoaclassbecauseacomponentormodulemaycontainmultipleclassesIwillusethetermlibrarytorefertoaphysicalcollection,orpackage,ofcomponents,thatis,library>modulecomponent>classThetermmethod,whilegenerallyunderstoodintheobjectorientedprogrammingcommunity,isnotstrictlyaCtermitoriginallyevolvedfromtheSmalltalklanguageTheequivalentCtermismemberfunction,althoughsomeengineerspreferthemorespecificdefinitionofvirtualmemberfunctionBecauseIamnotparticularlyconcernedwiththesubtletiesofthesetermsinthisbook,IwillusemethodandmemberfunctioninterchangeablySimilarly,althoughthetermdatamemberisthemorecorrectCexpression,IwilltreatthetermmembervariableasasynonymIntermsoftypographicalconventions,Iwilluseafixedwidthfonttotypesetallsourcecodeexamples,aswellasanyfilenamesorlanguagekeywordsthatmayappearinthetextAlso,IwillpreferuppercamelcaseforallclassandfunctionnamesintheexamplesthatIpresent,thatis,CamelCaseinsteadofcamelCaseorsnakecase,althoughobviouslyIwillpreservethecaseforanyexternalcodethatIreference,suchasstd::foreach()Ifollowtheconventionofusingan“m”prefixinfrontofdatamembers,forexample,mMemberVar,and“s”infrontofstaticvariables,forexample,sStaticVarItshouldbepointedoutthatthesourceexampleswithinthebookareoftenonlycodesnippetsandarenotmeanttoshowfullyfunctionalsamplesIwillalsooftenstripcommentsfromtheexamplecodeinthebookThisisdoneforreasonsofbrevityandclarityInparticular,IwilloftenomitanypreprocessorguardstatementsaroundaheaderfileIwillassumethatthereaderisawarethateveryCCheadershouldencloseallofitscontentwithinguardstatementsandthatit’sgoodpracticetocontainallofyourAPIdeclarationswithinaconsistentnamespace(ascoveredinChaptersand)Inotherwords,itshouldbeassumedthateachheaderfilethatIpresentisimplicitlysurroundedbycode,suchasthefollowing#ifndefMYMODULEH#defineMYMODULEHrequired#includefilesnamespaceapibook{APIdeclarations}#endifTIPIwillalsohighlightvariousAPIdesigntipsandkeyconceptsthroughoutthebookThesecalloutsareprovidedtoletyousearchquicklyforaconceptyouwishtorereadIfyouareparticularlypressedfortime,youcouldsimplyscanthebookforthesetipsandthenreadthesurroundingtexttogaingreaterinsightforthosetopicsthatinterestyouthemostBOOKWEBSITEThisbookalsohasasupportingWebsite,http:APIBookcomOnthissiteyoucanfindgeneralinformationaboutthebook,aswellassupportingmaterial,suchasthecompletesetofsourcecodeexamplescontainedwithinthetextFeelfreetodownloadandplaywiththesesamplesyourselftheyweredesignedtobeassimpleaspossible,whilestillbeingusefulandillustrativeIhaveusedthecrossplatformCMakebuildsystemtofacilitatecompilingandlinkingtheexamplessotheyshouldworkonWindows,MacOSX,andUNIXoperatingsystemsIwillalsopublishanyinformationaboutnewrevisionsofthisbookandanyerrataonthisWebsite,aswellasusefullinkstootherrelatedAPIresourcesontheInternet,suchasinterestingtoolkits,xxiPrefacearticles,andutilitiesThebookWebsitealsoprovidesaccesstoautilitythatIwrotecalledAPIDiffThisprogramletsyoucomparetwoversionsofanAPIandreviewdifferencestocodeorcommentsinavisualsidebysideformatYoucanalsogenerateareportofeverythingthatchangedinaparticularreleasesothatyourclientsknowexactlywhattolookoutforThisutilityisavailableforWindows,MacOSX,andLinuxportedmethroughoutthewholeprocess,whilealsoknowingexactlywhentomakemepauseandtakeabreakThankyouGenevieveforyourconstantloveandsupportxxiiiAcknowledgmentsThisbookhasbenefitedgreatlyfromthetechnicalreviewandfeedbackofseveralofmyesteemedcolleaguesIamindebtedtothemfortakingthetimetoreadearlyversionsofthemanuscriptandprovidethoughtfulsuggestionsforimprovementInparticular,IthankPaulStrauss,EricGregory,RychardeHawkes,NickLong,JamesChalfant,BrettLevin,MarcusMarr,JimHumelsine,andGeo

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +1积分

资料评分:

/49
仅支持在线阅读

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料