首页 > > > API Design for C++.pdf

API Design for C++.pdf

API Design for C++.pdf

上传者: tangwei19811102 2013-09-16 评分1 评论0 下载30 收藏10 阅读量1006 暂无简介 简介 举报

简介:本文档为《API Design for C++pdf》,可适用于专题技术领域,主题内容包含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

精彩专题

热门资料

多线程编程指南.pdf

Ubuntu12.10使用手册合集.pdf

智能社JS笔记--其他知识.doc

ORACLE数据库教程.ppt

编辑推荐

  • 名称/格式
  • 评分
  • 下载次数
  • 资料大小
  • 上传时间

用户评论

0/200
    暂无评论
上传我的资料

相关资料换一换

资料评价:

/ 446
所需积分:1 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!