1 / 28

Programming Style

Programming Style. Perspective Naming Conventions General Considerations Naming and Types Informal Formal (e.g., Hungarian) Names to Avoid Layout fundamentals and perspectives Commenting. Perspective. Programming is like writing for two audiences Computer

udell
Download Presentation

Programming Style

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming Style • Perspective • Naming Conventions • General Considerations • Naming and Types • Informal • Formal (e.g., Hungarian) • Names to Avoid • Layout fundamentals and perspectives • Commenting

  2. Perspective • Programming is like writing for two audiences • Computer • Yourself and other programmers • Should be as simple as possible • Identify how to the computer • Identify what to other programmers (the code communicates the how) • Take the perspective of an author writing a novel • Programming as literature

  3. Function and Procedure Names • For procedure name in non-Object-orient languages • Strong verb followed by an object (noun) • For object-oriented languages use a strong verb • Avoid wishy-washy verbs (e.g., handle, process, perform) • Describe everything the module does (too long many indicate low cohesion) • Make names as long as necessary (20-35 chars versus 15-20) • Establish conventions (e.g., get, set, increment, initialize)

  4. General Considerations • Naming has high impact to readability and maintainability, but often overlooked area of SW Engineering. • Fundamental consideration: • Name fully and accurately reflects • Everything the function or procedure does • what the data represpends • Example: • getCollectionFrequency(String term, int collectionId) • getNumberOfDocumentsContainingTerm(String term, int collectionId) • Orientation should be on problem not solution

  5. Optimal Name Length • Studies have found effort to debug correlated with length of name. • Gorla, etc. al. Effort to debug minimized with 10-16 char variable names, 8 -20 almost as easy • Scope and variable names • shorter names for limited scope • longer names for global variables • should we always use i and j within a loop • Can a name be too long? • Does a name ever affect performance of a system?

  6. Computed Value Qualifiers • Computed values include: totals, averages, maximums • Typically modified with: Total, Sum, Count, Avg, Max, Min • Should put modifier at end • revenueTotal verus totalRevenue • Advantages: most important part first, avoids confusion, consistent • Exception is Num qualifier • NumSales versus SalesNum • Sidestep by using count for count and index for indexes

  7. Loop Indexes • Example For i := FirstItem to LastItem do … • Avoid using i,j,k • Altogether • When used outside loop • When used in calculations • When loop is deeply nexed • When referencing multi-dimensional arrays? • Others?

  8. Status Variables • Avoid using the terms status and flag by themselves • Instead: • Done--when something is done or complete • Found--to indicate when something is found (better yet, use as qualifier, maximumAccountFound) • Error--to indicate an error has occurred (better yet, use as qualifier, divideByZeroError) • Success--to indicate an operation has been successful • Avoid negative names (e.g., notFound, notSuccessful)

  9. Naming Convention • Avoid having to make decision over and over again • Transfer knowledge across projects • Learn code more quickly • Reduce name proliferation (reduces total name sapce) • Compensate for language weaknesses • Emphasize relationships between related items

  10. Informal Naming Conventions • Identify global variables (e.g., all capitals, or g_ prefix) • Identify module variables (e.g., m_ prefix) • Identify type definitions (e.g., _t in Pascal, uppercase followed by _t in C) • Identify named constants (e.g., capitalized followed by _c) • Identify input / output parms in languages that don’t enforce them (what to do in Java?)

  11. Hungarian Notation • Created by Charles Simonyi • Widely used in C • Three parts • base type • one or more prefixes • qualifier • Base types (examples) • wn Window • scr Screen • fon Font • Define data types using same abbreviations • WN wnMain • SCR scrUserSpace

  12. Hungarian Notation • Prefixes describe the use of a variable • a Array • c Count • d Difference • e Array Element • Prefixes are lowercase and go before the base type, for example • awn is an array of windows • ewn is an element of the array • cfon count of the number of fonts

  13. Qualifiers • Qualifier is the descriptive part of the name • It’s what you would use if you weren’t using HN • In addition, there are some standards • Min (first element of an ordered collection) • First (first element that needs to be dealt with, contrast with Min) • Last (last element that needs to be dealt with, see First) • Lim (Upper limit on array, typically Last + 1) • Max (see Min)

  14. Examples for ( ipaReformat = ipaFirstReformat; ipaReformat <= ipaLastReformat ipraReformat++)… or for ( ipaReformat = ipaFirstReformat; ipaReformat < ipaLimitReformat ipraReformat++)… ich an index into an array of characters pachInsert a pointer into an array of characters to insert ppach a pointer to a pointer to an array of characters

  15. Pros and Cons • Pros • General advantage of naming convention • Fewer names to remember • Several levels of precision • Check types • Document types in weakly typed languages • Makes names compact • Cons • Some versions ignore ADT as base types • Conflates meaning and representation • Encourages lazy, uninformative variables names • Is HN needed in modern IDE (e.g., that support quick type lookup, etc)

  16. Layout Fundamentals • Fundamental theorem of formatting • Good layout highlights the logical structure of a program • Pretty code it nice, but not at the expense of highlighting structure • Logical structure usually implies pretty code • Pretty code doesn’t necessarily highlight logical structure • Layout has a significant impact of readability and maintainability of the code

  17. Layout Objectives • Objectives • Accurately represent logical structure of program • the primary focus of layout • accomplished primarily through indentation and whitespace • Consistently represent logical structure (I.e., avoid styles with too many exceptions) • Improve readability • Withstand modification • Weighting criteria differently might lead to different conclusions

  18. Tools of Layout • McConnell mentions • Whitespace • Grouping • Blank Lines • Alignment • Indentation • Parenthesis • Others might includes • Typeface • Shading • Color • Popups • Why aren’t these techniques used more?

  19. Comments • Five kinds of comments • Repeat of the code (avoid) • Explanation of code (use sparingly) • Marker in code • Summary of code (use description of intent instead) • Description of intent of code • Commenting efficiently • Use styles that don’t break down with modification • Outline the code in comments • Comment as you go (should you avoid breaking your concentration?)

  20. Commenting Suggestions • Individual lines comments (need is rare) • Endline comments • Avoid except for: • Annotate data declarations • Comment maintenance notes (e.g., {fixed error # 99}) • Mark end of blocks (when not obvious) • Module comments (aka paragraph comments) • Write comment at level of code’s intent (I.e., what not how) • Comment should add something code doesn’t say

  21. Inner Module Comments • Don’t comment tricky code • Exactly the wrong approach, simplify, simplify, simplify • Good code is like good writing (simple as possible to communicate the idea) • Comment surprises (different than tricky code) • Comment anything that gets around an error on undocumented feature • Justify violations of standards or conventions

  22. Commenting Data Declarations • Units of measure: • (e.g., miles, metric tons, gallons) • what about? setAge(int age) • Range of allowable input [ versus ) • Coded meanings (e.g., -1 means undefined) • Limitations • Stamp comment with name of variable to flag in updates • Global data: both set, use, and why it is global

  23. Control Structures • Purpose of a loop • Before each block of statements • End of the control structure /** * Returns true if the square of an itemToSquare is in the searchSpace, * otherwise returns false. */ public boolean findSquare2(int itemToSquare, int [] searchSpace) { // searchTerm is the item we're searching for int searchTerm = itemToSquare * itemToSquare; int lastIndex = searchSpace.length -1; // keep the last element for comparison and replace the last // element with a sentinel (i.e., what we're searching for int lastElement = searchSpace[lastIndex]; searchSpace[lastIndex] = searchTerm; int i = 0; // Loop until we find the searchTerm (which might be the sentinel) for (i=0; searchSpace[i] != searchTerm; i++) { // Do nothing in the body of the loop. } // Exit when we've either found the item or we're at the end // Replace the last element with the original value searchSpace[lastIndex] = lastElement; // return true if we've found the item otherwise false return i < lastIndex || searchTerm == lastElement; }

  24. Routines • Use a template: • Name: • Purpose • Algorithm • Inputs • Outputs • Interface Assumptions • Modification History • Note that some of this is handled already by JavaDoc or other such documentation tools

  25. Check List (McConnell) • General • Does the source listing contain most of the information about the program? • Can someone pick up the code and immediately start understanding it? • Do comments explain the code's intent or summarize it, rather than just repeating it? • Has tricky code been rewritten rather than commented? • Does the comment style allow comments to be easily modified?

  26. Check List (McConnell) • Statements and Paragraphs • Does the code avoid endline comments? • Do comments focus on why rather than how? • Do comments prepare the reader's mind for what is to follow? • Does every comment count? Have redundant, extraneous, or self-indulgent comments been removed or improved? • Are surprises documented? • Have abbreviations been replaced? • Is the distinction between major and minor comments clear? • Is code that works around an error or undocumented feature commented?

  27. Check List (McConnell) • Data Declarations • Are units on data declarations commented? • Is the range of values on numeric data commented? • Are coded meanings commented? • Are limitations on input data commented? • Are flags documented to the bit level? • Has each global variable been commented where it is declared? • Has each global variable been documented each time it's used, either with a naming convention or a comment? Control Structures • Is each control statement commented? • Are the ends of long or complex control structures commented? • Are magic numbers documented or, preferably, replaced with named constants or variables?

  28. Check List (McConnell) • Routines • Is the purpose of each routine commented? • Are other facts of each routine given in comments, when relevant, including input and output data, interface assumptions, limitations, error corrections, global effects, and sources of algorithms? • Files, Modules, and Programs • Does the program have a 4 to 5 page document such as that described in The Book Paradigm that gives an overall view of how the program is organized? • Is the purpose of each file described? • Is the author's name and phone number in the listing?

More Related