programming style n.
Skip this Video
Loading SlideShow in 5 Seconds..
Programming Style PowerPoint Presentation
Download Presentation
Programming Style

Loading in 2 Seconds...

play fullscreen
1 / 28

Programming Style - PowerPoint PPT Presentation

  • Uploaded on

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

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Programming Style' - udell

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
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
  • 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
function and procedure names
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)
general considerations
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
optimal name length
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?
computed value qualifiers
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
loop indexes
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?
status variables
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)
naming convention
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
informal naming conventions
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?)
hungarian notation
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
hungarian notation1
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
  • 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)

for (

ipaReformat = ipaFirstReformat;

ipaReformat <= ipaLastReformat



for (

ipaReformat = ipaFirstReformat;

ipaReformat < ipaLimitReformat


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

pros and cons
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)
layout fundamentals
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
layout objectives
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
tools of layout
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?
  • 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?)
commenting suggestions
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
inner module comments
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
commenting data declarations
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
control structures
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;


  • 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
check list mcconnell
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?
check list mcconnell1
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?
check list mcconnell2
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?
check list mcconnell3
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?