爱问 爱问共享资料 爱问分类
首页 >IT资料 >专题技术 >API Design for C++.pdf

API Design for C++.pdf

上传者: tangwei19811102
30次下载 0人收藏 暂无简介 简介 2013-09-16 举报

简介:API Design for C++,从另一个角度阐述了C++如何设计API,值得一看。

APIDesignforC++APIDesignforC++MartinReddyAMSTERDAM•BOSTON•HEIDELBERG•LONDONNEWYORK•OXFORD•PARIS•SANDIEGOSANFRANCISCO•SINGAPORE•SYDNEY•TOKYOMorganKaufmannPublishersisanimprintofElsevierAcquiringEditor:ToddGreenNopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,oranyinformationstorageandretrievalsystem,withoutpermissioninwritingfromthepublisher.Detailsonhowtoseekpermission,furtherinformationaboutthePublisher’spermissionspoliciesandourarrangementswithorganizationssuchastheCopyrightClearanceCenterandtheCopyrightLicensingAgency,canbefoundatourwebsite:www.elsevier.com/permissions.ThisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythePublisher(otherthanasmaybenotedherein).NoticesKnowledgeandbestpracticeinthisfieldareconstantlychanging.Asnewresearchandexperiencebroadenourunderstanding,changesinresearchmethodsorprofessionalpracticesmaybecomenecessary.Practitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluatingandusinganyinformationormethodsdescribedherein.Inusingsuchinformationormethodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,includingpartiesforwhomtheyhaveaprofessionalresponsibility.Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assumeanyliabilityforanyinjuryand/ordamagetopersonsorpropertyasamatterofproductsliability,negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideascontainedinthematerialherein.LibraryofCongressCataloging-in-PublicationDataApplicationsubmittedBritishLibraryCataloguing-in-PublicationDataAcataloguerecordforthisbookisavailablefromtheBritishLibrary.ISBN:9780123850034PrintedintheUnitedStatesofAmerica1112131410987654321EditorialAssistant:RobynDayProjectManager:AndreCuelloDesigner:EricDeCiccoMorganKaufmannisanimprintofElsevier30CorporateDrive,Suite400,Burlington,MA01803,USA#2011Elsevier,Inc.Allrightsreserved.ForinformationonallMKpublicationsvisitourwebsiteatwww.mkp.comForewordIshouldbeginbyconfessingthatIdonotconsidermyselfaworld-classAPIdesignerorsoftwareengineer.Ido,however,considermyselfanexpertresearcherintheareasofcomputergraphicsandgeometricmodeling.ItwasinthislineofworkthatIfirstmetMartinatPixarAnimationStudios.xvAsagraphicsresearcherIwasaccustomedtowritingmathematicallysophisticatedpapers.Iwasalsoformallytrainedasacomputerscientistatamajoruniversityandhadwrittenmyshareofcode.Armedwiththisbackground,whenIwaspresentedwiththeopportunitytoleadagroupofsoftwareengineersworkingonanewgenerationofanimationsoftwareforPixar,Ifiguredthatitcouldn’tbeanymoredifficultthanresearch.Afterall,researchis,bydefinition,thecreationoftheunknown,whereasengineeringistheimplementationofwell-understoodsubjects.Icouldnothavebeenmorewrong.Icametorealizethatsoftwareengineeringwas,withoutadoubt,themostdifficultchallengeIhadeverbeenpresentedwith.AftermoreyearsthanIcaretoadmit,Ieventuallygaveupandwentbacktographicsresearch.Ican’ttellyouhowmuchIwouldhavebenefittedfromabooksuchas“APIDesignforC++.”ManyofthelessonswelearnedthehardwayhavebeencapturedbyMartininthisinsightful,easy-to-usebook.Martinapproachesthesubjectnotfromtheperspectiveofanacademicsoftwareresearcher(althoughhedrawsheavilyfromresultsandinsightsgainedthere),butfromtheperspec-tiveofanin-the-trenchessoftwareengineerandmanager.Hehasexperiencedfirsthandtheimportanceofgoodsoftwaredesignandhasemergedasanarticulatevoiceofwhat“good”means.Inthisbookhepresentseffectivestrategiesforachievingthatgoal.IparticularlylikethatMartinisnotfocusingjustonAPIdesign,butmorebroadlyonsoftwarelifecycles,allowinghimtocovertopicssuchasversioning,strategiesforbackwardcompatibility,andbranchingmethodologies.Inshort,thisbookshouldbeofgreatvaluetothosecreatingormanagingsoftwareactivities.Itisacomprehensivecollectionofbestpracticesthathaveproventhemselvestimeandtimeagain.TonyDeRoseSeniorScientistandResearchGroupLead,PixarAnimationStudiosAnAPIpresentsalogicalinterfacetoasoftwarecomponentandhidestheinternaldetailsrequiredtoimplementthatcomponent.Itoffersahigh-levelabstractionforamoduleandpromotesmorecostlytofixthanabuginyourimplementation.Forinstance,aninterfacechangemayrequirealloftheapplicationsbasedonyourcodetobeupdated,whereasanimplementacanbeintegratedtransparentlyandeffortlesslyintoclientapplicationswhenthetion-onlychangeyadoptthenewxviicodereusebyallowingmultipleapplicationstosharethesamefunctionality.ModernsoftwaredevelopmenthasbecomehighlydependentonAPIs,fromlow-levelapplicationframeworkstodataformatAPIsandgraphicaluserinterface(GUI)frameworks.Infact,commonsoftwareengineeringtermssuchasmodulardevelopment,codereuse,componentization,dynamiclinklibraryorDLL,softwareframeworks,distributedcomputing,andservice-orientedarchitectureallimplytheneedforstrongAPIdesignskills.SomepopularCandC++APIsthatyoumayalreadybeawareofincludetheStandardTemplateLibrary(STL),Boost,theMicrosoftWindowsAPI(Win32),MicrosoftFoundationClasses(MFC),libtiff,libpng,zlib,libxml++,OpenGL,MySQL++,Trolltech’sQt,wxWidgets,GTK+,KDE,Sky-peKit,POSIXpthreads,Intel’sThreadingBuildingBlocks,theNetscapePluginAPI,andtheApachemoduleAPI.Inaddition,manyofGoogle’sopen-sourceprojectsareC++,asismuchofthecodeonthesourceforge.net,bitbucket.org,andfreshmeat.netWebsites.APIssuchastheseareusedinallfacetsofsoftwaredevelopment,fromdesktopapplications,tomobilecomputingandembeddedsystems,toWebdevelopment.Forexample,theMozillaFirefoxWebbrowserisbuiltontopofmorethan80dynamiclibraries,eachofwhichprovidestheimple-mentationforoneormoreAPIs.ElegantandrobustAPIdesignisthereforeacriticalaspectofcontemporarysoftwaredevelop-ment.Oneimportantwayinwhichthisdiffersfromstandardapplicationdevelopmentisthefargreaterneedforchangemanagement.Asweallknow,changeisaninevitablefactorinsoftwaredevelopment;newrequirements,featurerequests,andbugfixescausesoftwaretoevolveinwaysthatwereneveranticipatedwhenitwasfirstdevised.However,changestoanAPIthatissharedbyhundredsofend-userapplicationscancausemajorupheavalandultimatelymaycauseclientstoabandonanAPI.TheprimarygoalofgoodAPIdesignisthereforetoprovideyourclientswiththefunctionalitytheyneedwhilealsocausingminimalimpacttotheircodeideallyzeroimpactwhenyoureleaseanewversion.WHYYOUSHOULDREADTHISBOOKIfyouwriteC++codethatanotherengineerreliesupon,you’reanAPIdesignerandthisbookhasbeenwrittenforyou.InterfacesarethemostimportantcodethatyouwritebecauseaproblemwithyourinterfaceisfarPrefaceWritinglargeapplicationsinC++isacomplexandtrickybusiness.However,designingreusableC++interfacesthatarerobust,stable,easytouse,anddurableisevenmoredifficult.Thebestwaytosuc-ceedinthisendeavoristoadheretothetenetsofgoodApplicationProgrammingInterface(API)design.implementation,testing,documentation,release,versioning,maintenance,anddeprecation.IwillxviiiPrefaceevencoverspecializedAPItopicssuchascreatingscriptingandpluginAPIs.Whilemanyofthesetopicsarealsorelevanttosoftwaredevelopmentingeneral,thefocusherewillbeontheparticularimplicationsforAPIdesign.Forexample,whendiscussingtestingstrategiesIwillconcentrateonautomatedAPItestingtechniquesratherthanattemptingtoincludeend-userapplicationtestingtechniquessuchasGUItesting,systemtesting,ormanualtesting.Intermsofmyowncredentialstowritethisbook,IhaveledthedevelopmentofAPIsforresearchcodesharedbyseveralcollaboratinginstitutions,in-houseanimationsystemAPIsthathavebeenusedtomakeAcademyAward-winningmovies,andopen-sourceclient/serverAPIsthathavebeenusedbymillionsofpeopleworldwide.Throughoutallofthesedisparateexperiences,Ihaveconsistentlywit-nessedtheneedforhigh-qualityAPIdesign.Thisbookthereforepresentsapracticaldistillationofthetechniquesandstrategiesofindustrial-strengthAPIdesignthathavebeendrawnfromarangeofreal-worldexperiences.WHOISTHETARGETAUDIENCEWhilethisbookisnotabeginner’sguidetoC++,Ihavemadeeveryefforttomakethetexteasytoreadandtoexplainallterminologyandjargonclearly.ThebookshouldthereforebevaluabletonewprogrammerswhohavegraspedthefundamentalsofC++andwanttoadvancetheirdesignskills,aswellasseniorengineersandsoftwarearchitectswhoareseekingtogainnewexpertisetocomple-menttheirexistingtalents.TherearethreespecificgroupsofreadersthatIhaveborneinmindwhilewritingthisbook.1.Practicingsoftwareengineersandarchitects.JuniorandseniordeveloperswhoareworkingonaspecificAPIprojectandneedpragmaticadviceonhowtoproducethemostelegantandenduringdesign.2.Technicalmanagers.ProgramandproductmanagerswhoareresponsibleforproducinganAPIproductandwhowanttogaingreaterinsightintothetechnicalissuesanddevelopmentprocessesofAPIdesign.APIversion.Putinmoreeconomicterms,apoorlydesignedinterfacecanseriouslyreducethelong-termsurvivalofyourcode.Learninghowtocreatehigh-qualityinterfacesisthereforeanessentialengineeringskill,andthecentralfocusofthisbook.AsMichiHenningnoted,APIdesignismoreimportanttodaythanitwas20yearsago.ThisisbecausemanymoreAPIshavebeendesignedinrecentyears.Thesealsoprovidericherandmorecomplexfunctionalityandaresharedbymoreend-userapplications(Henning,2009).Despitethisfact,nootherbookscurrentlyonthemarketconcentrateonthetopicofAPIdesignforC++.It’sworthnotingthatthisbookisnotmeanttobeageneralC++programmingguidetherearealreadymanygoodexamplesoftheseonthemarket.Iwillcertainlycoverlotsofobject-orienteddesignmaterialandpresentmanyhandyC++tipsandtricks.However,IwillfocusontechniquesforrepresentingcleanmodularinterfacesinC++.Bycorollary,Iwillnotdiveasdeeplyintothequestionofhowtoimplementthecodebehindtheseinterfaces,suchasspecificalgorithmchoicesorbestpracticeslimitedtothecodewithinthecurlybracesofyourfunctionbodies.However,thisbookwillcoverthefullbreadthofAPIdevelopment,frominitialdesignthroughxixPrefaceCONVENTIONSWhileitismoretraditionaltoemploytheterm“user”tomeanapersonwhousesasoftwareappli-cation,suchasauserofMicrosoftWordorMozillaFirefox,inthecontextofAPIdesignIwillapplythetermtomeanasoftwaredeveloperwhoiscreatinganapplicationandisusinganAPItoachieveFOCUSINGONC++WhiletherearemanygenericAPIdesignmethodologiesthatcanbetaughtskillsthatapplyequallywelltoanyprogramminglanguageorenvironmentultimatelyanAPIhastobeexpressedinapar-ticularprogramminglanguage.Itisthereforeimportanttounderstandthelanguage-specificfeaturesthatcontributetoexemplaryAPIdesign.ThisbookisthereforefocusedontheissuesofdesigningAPIsforasinglelanguage(C++)ratherthandilutingthecontenttomakeitapplicableforalllanguages.WhilereaderswhowishtodevelopAPIsforotherlanguages,suchasJavaorC#,maystillgainmuchgeneralinsightfromthistext,thebookisdirectlytargetedatC++engineerswhomustwriteandmaintainAPIsforotherengineerstoconsume.C++isstilloneofthemostwidelyusedprogramminglanguagesforlargesoftwareprojectsandtendstobethemostpopularchoiceforperformance-criticalcode.Asaresult,therearemanydiverseCandC++APIsavailableforyoutouseinyourownapplications(someofwhichIlistedearlier).IwillthereforeconcentrateonaspectsofproducinggoodAPIsinC++andincludecopioussourcecodeexamplestoillustratetheseconceptsbetter.ThismeansthatIwilldealwithC++-specifictopicssuchastemplates,encapsulation,inheritance,namespaces,operators,constcorrectness,memorymanagement,useofSTL,thepimplidiom,andsoon.Additionally,thisbookwillbepublishedduringanexcitingtimeintheevolutionofC++.AnewversionoftheC++specificationiscurrentlyworkingitswaythroughtheISO/IECstandardizationprocess.MostC++compilerscurrentlyaimtoconformtothestandardthatwasfirstpublishedin1998,knownasC++98.Alaterrevisionofthisstandardwaspublishedin2003tocorrectseveraldefects.Sincethattime,thestandardscommitteehasbeenworkingonamajornewversionofthespecification.ThisversionisreferredtoinformallyasC++0x,untilsuchtimethatthestandardisrati-fiedandthedateofpublicationisknown.Bythetimeyoureadthisbook,thenewstandardwilllikelyhavebeenpublished.However,atthetimeofwriting,itisstillreferredtoasC++0x.Nonetheless,C++0xhasreachedanadvancedstageofthestandardizationprocess,andmanyofthenewfeaturescanbepredictedwithrelativelyhighconfidence.Infact,someofthemajorC++compilershavealreadystartedtoimplementmanyoftheproposednewfeatures.IntermsofAPIdesign,severalofthesenewlanguagefeaturescanbeusedtoproducemoreelegantandsturdyinter-faces.Assuch,IhaveendeavoredtohighlightandexplainthoseareasofC++0xthroughoutthebook.Thisbookshouldthereforeremainarelevantresourceforseveralyearstocome.3.Studentsandeducators.Computerscienceandsoftwareengineeringstudentswhoarelearninghowtoprogramandareseekingathoroughresourceonsoftwaredesignthatisinformedbyprac-ticalexperienceonlarge-scaleprojects.xxPrefacethis.Inotherwords,IwillgenerallybetalkingaboutAPIusersandnotapplicationusers.Theterm“client”willbeusedsynonymouslyinthisregard.Notethattheterm“client,”inadditiontoreferringtoahumanuserofyourAPI,canalsoreferimpersonallytootherpiecesofsoftwarethatmustcallfunctionsinyourAPI.WhiletherearemanyfileformatextensionsusedtoidentifyC++sourceandheaderfiles,suchas.cpp,.cc,.cxx,.h,.hh,and.hpp,Iwillstandardizeontheuseof.cppand.hthroughoutthisbook.“Iwillalsousethetermsmoduleandcomponent”interchangeablytomeanasingle.cppand.hfilepair.Thesearenotablynotequivalenttoaclassbecauseacomponentormodulemaycontainmulti-pleclasses.Iwillusethetermlibrarytorefertoaphysicalcollection,orpackage,ofcomponents,thatis,library>module/component>class.Thetermmethod,whilegenerallyunderstoodintheobject-orientedprogrammingcommunity,isnotstrictlyaC++term;itoriginallyevolvedfromtheSmalltalklanguage.TheequivalentC++termismemberfunction,althoughsomeengineerspreferthemorespecificdefinitionofvirtualmemberfunction.BecauseIamnotparticularlyconcernedwiththesubtletiesofthesetermsinthisbook,Iwillusemethodandmemberfunctioninterchangeably.Similarly,althoughthetermdatamemberisthemorecorrectC++expression,Iwilltreatthetermmembervariableasasynonym.Intermsoftypographicalconventions,Iwilluseafixed-widthfonttotypesetallsourcecodeexamples,aswellasanyfilenamesorlanguagekeywordsthatmayappearinthetext.Also,IwillpreferuppercamelcaseforallclassandfunctionnamesintheexamplesthatIpresent,thatis,CamelCaseinsteadofcamelCaseorsnakecase,althoughobviouslyIwillpreservethecaseforanyexternalcodethatIreference,suchasstd::foreach().Ifollowtheconventionofusingan“m”prefixinfrontofdatamembers,forexample,mMemberVar,and“s”infrontofstaticvariables,forexample,sStaticVar.Itshouldbepointedoutthatthesourceexampleswithinthebookareoftenonlycodesnippetsandarenotmeanttoshowfullyfunctionalsamples.Iwillalsooftenstripcommentsfromtheexam-plecodeinthebook.Thisisdoneforreasonsofbrevityandclarity.Inparticular,Iwilloftenomitanypreprocessorguardstatementsaroundaheaderfile.IwillassumethatthereaderisawarethateveryC/C++headershouldencloseallofitscontentwithinguardstatementsandthatit’sgoodprac-ticetocontainallofyourAPIdeclarationswithinaconsistentnamespace(ascoveredinChapters3and6).Inotherwords,itshouldbeassumedthateachheaderfilethatIpresentisimplicitlysur-roundedbycode,suchasthefollowing.#ifndefMYMODULEH#defineMYMODULEH//required#includefiles...namespaceapibook{//APIdeclarations...}#endifTIPIwillalsohighlightvariousAPIdesigntipsandkeyconceptsthroughoutthebook.Thesecalloutsareprovidedtoletyousearchquicklyforaconceptyouwishtoreread.Ifyouareparticularlypressedfortime,youcouldsimplyscanthebookforthesetipsandthenreadthesurroundingtexttogaingreaterinsightforthosetopicsthatinterestyouthemost.BOOKWEBSITEThisbookalsohasasupportingWebsite,http://APIBook.com/.Onthissiteyoucanfindgeneralinformationaboutthebook,aswellassupportingmaterial,suchasthecompletesetofsourcecodeexamplescontainedwithinthetext.Feelfreetodownloadandplaywiththesesamplesyourselftheyweredesignedtobeassimpleaspossible,whilestillbeingusefulandillustrative.Ihaveusedthecross-platformCMakebuildsystemtofacilitatecompilingandlinkingtheexamplessotheyshouldworkonWindows,MacOSX,andUNIXoperatingsystems.IwillalsopublishanyinformationaboutnewrevisionsofthisbookandanyerrataonthisWebsite,aswellasusefullinkstootherrelatedAPIresourcesontheInternet,suchasinterestingtoolkits,xxiPrefacearticles,andutilities.ThebookWebsitealsoprovidesaccesstoautilitythatIwrotecalledAPIDiff.ThisprogramletsyoucomparetwoversionsofanAPIandreviewdifferencestocodeorcommentsinavisualside-by-sideformat.Youcanalsogenerateareportofeverythingthatchangedinaparticularreleasesothatyourclientsknowexactlywhattolookoutfor.ThisutilityisavailableforWindows,MacOSX,andLinux.portedmethroughoutthewholeprocess,whilealsoknowingexactlywhentomakemepauseandtakeabreak.ThankyouGenevieveforyourconstantloveandsupport.xxiiiAcknowledgmentsThisbookhasbenefitedgreatlyfromthetechnicalreviewandfeedbackofseveralofmyesteemedcolleagues.Iamindebtedtothemfortakingthetimetoreadearlyversionsofthemanuscriptandprovidethoughtfulsuggestionsforimprovement.Inparticular,IthankPaulStrauss,EricGregory,RychardeHawkes,NickLong,JamesChalfant,BrettLevin,MarcusMarr,JimHumelsine,andGeo

相关资料推荐

  • 名称/格式
  • 下载次数
  • 资料大小

用户评论

0/200
暂无评论

该用户的其它资料

关闭

请选择举报的类型

关闭

提示

提交成功!

感谢您对爱问共享资料的支持,我们将尽快核实并处理您的举报信息。

关闭

提示

提交失败!

您的举报信息提交失败,请重试!

关闭

提示

重复举报!

亲爱的用户!感觉您对爱问共享资料的支持,请勿重复举报噢!

全屏 缩小 放大
收藏
资料评价:

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

温馨提示

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