软件工程课件:06-CodingStyle_第1页
软件工程课件:06-CodingStyle_第2页
软件工程课件:06-CodingStyle_第3页
软件工程课件:06-CodingStyle_第4页
软件工程课件:06-CodingStyle_第5页
已阅读5页,还剩65页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Outline1Defensive programmingLayout and presentationNaming conventionSelf-documenting codeCode commentsCode CraftTo write the right code, in the right way Crafting technically elegant codeCreating maintainable code that others can interpretUnderstanding and adapting other peoples messy codeWorking w

2、ell alongside other programmers23Hunt&Thomas 2000McConnell 2004GoodLiffe 2007Defensive programming4害人之心不可有防人之心不可无The lessons of ArianeOn June 4, 1996, the maiden flight of European Ariane 5 launcher crashed, about 40 second after takeoff. Media reports indicated that a half-billion dollars was lost

3、the rocket was uninsured. 5How in the world could such a trivial error have remained undetected and cause a $500 million rocket to blow up. The lessons of ArianeThe explosion is the result of a software error due to an uncaught exception. The error from a piece of software that was NOT needed. The e

4、xception was due to a floating point error during a conversion from a 64-bit floating-point value, representing the flights “horizontal bias”, to a 16-bit signed integer. That is, the value that was converted was greater than what can be represented as a 16-bit singed integer. The uncaught exception

5、 crashed the entire software, hence the onboard computers, hence the mission. 6The lessons of ArianeVulnerabilityAnalysisTheoreticalAnalysisVariable should be protected!Overflow Could not happen80% workload targetPerformanceConstraintsEngineering Compromise:Remove the conversion protection to achiev

6、e more performanceIt was right for Ariane 4, but did not hold for Ariane 5!7The Murphys Law“If anything can go wrong, it will” (怕什么来什么)“If there is more than one possible outcome of a job or task, and one of those outcomes will result in disaster or an undesirable consequence, then somebody will do

7、it that way.”If your code can be used incorrectly, it will be. 8Defensive Programming9The function will crash when the input is over 1000 characters. However, many mainstream programmers may not feel that this is a problem because “Surely no one will enter that long of an input!”Defensive Programmin

8、gAssume nothing. Unwritten assumptions continually cause faults, particularly as code grows. 10Garbage in, garbage outGarbage in, nothing outDefensive protectionGarbage in, error message outNo garbage allowed inDefensive ProgrammingEncourage programmers to include as many checks as possibleCheck the

9、 values of all data from external sourcesCheck the values of all input parametersDecide how to handle bad inputs11For and AgainstAgainstForIt eats into the efficiency of your code Each defensive practice requires some extra workSave you literally hours of debugging Working code that runs properly, b

10、ut ever-so-slightly slower, is far superior to code that works most of the time but occasionally collapses in a shower of brightly colored sparks. 12Contracting SoftwareObjects in a system communicate as clients and servers.Communication is regulated through clear responsibilities for involved parti

11、es. Both clients and servers in communication have defined benefits and obligations13Elements of ContractsPre-conditionThe conditions that must be hold before a method can executeEvaluated before a method executesThe obligations that a client of a software component must meet before it may invoke pa

12、rticular method of the component Post-conditionThe conditions that must hold after a method completes. Evaluated after a method completes. Ensure that a software component makes to its clientsInvariantsThe condition that must hold anytime a client could invoke an objects method. Evaluated anytime 14

13、Design by Contract (DbC) with EiffelThe Eiffel programming language was created by Bertrand Meyer in 1985. 15An ExampleA class TREE describing tree nodes, a routine put_child for adding a new child to a tree node Current. 16Programming with AssertionsAn assertion is a statement in the JavaTM program

14、ming language that enables you to test your assumptions about your program. Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error.assert Expression1 ;assert Expression1 : Expression2 ;Experience has s

15、hown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs.1718if (i % 3 = 0) . else if (i % 3 = 1) . else / We know (i % 3 = 2) . if (i % 3 = 0) . else if (i % 3 = 1) . else assert i % 3 = 2 : i; . switch(suit) case Suit.CLUBS: . break;

16、case Suit.DIAMONDS: . break; case Suit.HEARTS: . break; case Suit.SPADES: . switch(suit) case Suit.CLUBS: . break; . default: assert false : suit; switch(suit) case Suit.CLUBS: . break; . default: throw new AssertionError(suit); Internal Invariants19Pre-conditions/* * Sets the refresh interval (whic

17、h must correspond to a legal frame rate). * param interval refresh interval in milliseconds. */ private void setRefreshInterval(int interval) / Confirm adherence to precondition in nonpublic method assert interval 0 & interval = 1000/MAX_REFRESH_RATE : interval; . / Set the refresh interval Post-con

18、ditions/* Returns a BigInteger whose value is (this-1 mod m). * param m the modulus. * return this-1 mod m. * throws ArithmeticException m = 0, or this BigInteger has no multiplicative * inverse mod m (that is, this BigInteger is not relatively prime to m). */ public BigInteger modInverse(BigInteger

19、 m) if (m.signum =0; -i2) n1=n2; n2=ret; ret=n2+n1; return (i2)? 1:ret;int fibonacci (int position) for (position 2) return 1; int previousButOne = 1; int previous = 1; int answer= 2; for (int n=2; nposition; +n) previousButOne= previous;previous= answer;answer= previous + previousButOne; return ans

20、wer;The FACTEven the smallest, most beautiful functions will need later maintenance. TechniquesWrite simple code with good presentation Make the “normal” path through your code obvious. Your if-then-else constructs should be ordered consistently. Always place the “normal” case before the “error” cas

21、e, or vice versaAvoid too many nested statements.Balance between exist points (Single Input, Single Output) and nesting levels. Be wary of optimizing code so that its no longer a clear expression of a basic algorithm. Never optimize code unless youve proved that it is a bottleneck to acceptable prog

22、ram function. 4748int fibonacci (int position) for (position 2) return 1; int previousButOne = 1; int previous = 1; int answer= 2; for (int n=2; n= 2) int previousButOne = 1; int previous = 1; for (int n=2; nposition; +n) previousButOne = previous; previous = answer; answer = previous + previousButO

23、ne; return answer;Single exist, Deep nesting levelsTechniquesDecompose into Atomic FunctionsOne function, one action. Minimize any surprising side effectsKeep it shortGroup related information Use language features to make explicit grouping of related information. Emphasize important codeMake sure t

24、hat all important code stands out and is easy to read. Hide anything that the client audience doesnt care about. 49TechniquesChoose meaningful namesChoose Descriptive TypesName constants Avoid magic numbers. Use well-named constants instead. 50login21login22login2Xlogin32login31login3XMagic NumberIn

25、 a NutshellGood programmers Bad programmersSeek to write clear, self-documenting codeTry to write the least amount of documentation necessary Think about the needs of programmers who will maintain their code Are proud that they write unfathomable spaghetti (混乱复杂的程序)Try to avoid writing any documenta

26、tionDont care about updating documentation Think, “if it was hard for me to write, it should be hard for anyone to understand. ”53Code Comments545556/ write out the sums 1.n for all n from 1 to numcurrent = 1;previous =0;sum = 1;for (int i = 0; i num; i+) System.out.println (“Sum = “ + sum); sum = c

27、urrent + previous; previous = current; current = sum;/ set product to “base”product = base;/ loop from 2 to “num”for (int i = 2; i TOLERANCE) r = 0.5 * (r + (num/r);System.out.println (“r =“ + r ); Different types of commentsWrongXRepeat of the codeNice explanationTo Comment or Not to CommentComment

28、 are easier to write poorly than well, and commenting can be more damaging than helpful. We need to focus on comment quality, not quantity, so more important than the amount of comments we write are the contents of those comments. To write enough comments, and no more. 57Commenting Techniques Explai

29、n Why, Not HowDont describe the codeDont replace the codeKeep it usefulDocument the unexpectedTell the truthAre worthwhileAre clear5859blockSize = optimalBlockSize ( numItems, sizePerItem);/* The following code is necessary to work around an error in writeData () that appears only when the third par

30、ameter equals 500. 500 has been replaced With a named constant for clarity.*/if ( blockSize = WRITEDATA_BROKEN_SIZE ) blockSize = WRITEDATA_WORKAROUND_SIZE ;WriteData ( file, data, blockSize );int boundary = 0; / upper index of sorted part of arrayString insertVal = BLANK; / date elmt to insert in s

31、orted part of arrayont insertPos = 0; / poistion to insert elmt in sorted part of array/ swap the rootsoldRoot = root 0;root 0 = root 1;root 1 = oldRoot;for (element = 0; element 1;Commenting Techniques 60/ if account flag is zero if (accountFlag = 0) / if establishing a new account if (accountFlag

32、= 0) / if establishing a new account if (accountType = AccountType.NewAccount) / Establish a new account if (accountFlag = 0) Not necessary comment: repeat the codeGood comment to describe the intent of the codeGood Self-document codeNot necessary commentsImproved comments to summary the whole block

33、 of codeImprove commentsImprove codeImprove commentsCommenting Techniques Choose a low-maintenance style61/ variablemeaning/ -/ xPosXCoordinate Position (in meters)/ yPosYCoordinate Position (in meters)/* * Class: ABCD * * * * XXXXXXX */* Class: ABCD XXXXXXX */Style that is hard to maintainStyle tha

34、t is Much easier to maintainCommenting Techniques File Header Comments Describe the purpose and contents of each file Legal notice Avoid maintenance disasterA list of every function, class, global variable Rapidly out of dateVersions, modification history, Version control system tells you 62In a Nut

35、shellGood programmers Bad programmersTry to write a few really good commentsWrite comments explaining whyConcentrate on writing good code rather than a plethora of commentsWrite helpful comments that make senseCant tell the difference between good and bad commentsWrite comments explaining how Dont m

36、ind if comments only make sense to themselvesBolster bad code with many commentsFill their source files with redundant information63A Few More Words 64Programmers who program “in” a language limit thoughts to constructs that the language directly support. Programmers who program “into” a language fi

37、rst decide what thoughts they want to express, and then they determine how to express those thoughts using the tools provided their specific language. 65Programming “in” a languageProgramming “into” a languageVersusGries, David. 1981. The Science of Programming. New York. NY: Springer-Verlag. Checkl

38、ist: Major Construction PracticesCodeHave you defined coding conventions for names, comments, and layout?Have you defined specific coding practices that are implied by the architecture?How error conditions will be handled?What conventions will be used for class interfaces?What standards will apply t

39、o reused code?How much to consider performance while coding? ToolHave you selected a revision control tool?Have you selected a language and language version or compiler version?Have you selected a framework such as J2EE or Microsoft .NET or explicitly decided not to use a framework?Have you decided whether to allow use of nonstandard language features?Have you identified and acquired

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论