Programming Style
Perspective
Naming Conventions
— General Considerations
— Naming and Types
— Informal
— Formal (e.g., Hungarian)
— Names to Avoid
Layout fundamentals and
perspectives
CommentingPerspective
¢ 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 literatureFunction 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
* 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(S
tring term, int collectionId)
* Orientation should be on problem
not solutionOptimal 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 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 indexesLoop 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
¢ 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
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 itemsInformal 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 _tinC)
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
Created by Charles Simonyi
Widely used in C
Three parts
— base type
— one or more prefixes
— qualifier
Base types (examples)
— wn Window
— ser Screen
— fon Font
Define data types using same
abbreviations
— WN wnMain
— SCR scrUserSpaceHungarian 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 fontsQualifiers
* 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)Examples
for (
ipaReformat = ipaFirstReformat;
ipaReformat <= ipaLastReformat
ipraReformat+t)..
or
for (
ipaReformat = ipaFirstReformat;
ipaReformat < ipaLimitReformat
ipraReformatt+)...
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
charactersPros 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
¢ 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 codeLayout 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
conclusionsTools 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?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?)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 sayInner 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 conventionsCommenting 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 globalControl Structures
¢ Purpose of a loop
¢ Before each block of statements
¢ End of the control structure
pe
* Returns true if the square of an itemToSquare is in the searchSpace,
* otherwise retums false.
y
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];
searchSpacellastindex] = searchTerm;
int i = 0;
/! Loop until we find the searchTerm (which might be the sentinel)
for (i=0; searchSpace[i] != searchTerm; i++)
1/ 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;
/ retum true if we've found the item otherwise false
return i