Writing the programs
Programming standards
In this part we look at
Standards for programming
programming guidelines
using design to frame the code
internal and external documentation
Standards for you
Standards and procedures can help you
to organise your thoughts and avoid
mistakes.
Standardised documentation also helps
in locating faults and making changes,
because it clarifies which sections of
your program does what.
1
Programming standards
Standards for others
Once your code is complete it can be used in
a variety of ways.
A separate team may test the code.
Or a another team may integrate your software
with other programs to build and test subsystems
and finally the entire system.
You may not be part of any of those teams so
it is essential that you organise, format and
document your code to make it easy for
others to understand what it does and how it
3
works
Programming standards
Matching design with implementation
The most critical standard is the need
for a direct correspondence between
program design components and the
program code components.
The entire design process is of little
value if the design's modularity is not
carried forward into the code.
4
Programming guidelines
Programming guidelines
Each program involves at least three major
aspects:
control structures,
algorithms and
data structures.
Control structures are usually suggested by
the architecture and design and we want to
preserve them as the design is translated into
code. A rule of thumb is that they should be as
clear as possible with the flow going from top to
5
bottom.
Documentation
Algorithms are usually specified in the
program design. In particular, when
implementing algorithms do not
sacrifice clarity and correctness for
speed.
Data structures should be designed
such that data management and
manipulation are straightforward
6
Meaningful variable names
Internal documentation is descriptive material
written directly within the code; all other
documentation is external documentation.
Examples:
Choose names for your variables and
statements that reflect their use or
meaning.
weekswage = (hrrate * hours) +
0.5*(hrate)*(hours-40.0);
makes more sense to the reader than
a = (a*b) +(0.5) * (a) * (b- 40.0);
Header comment block
Other program comments
Meaningful variable names
Formatting to enhance understanding
Documenting data
7
Abstract
External documentation
The abstract summarizes the software's major
capabilities and purposes.
The ANSI standard for software
documentation
makes recommendations for the content rather
than the form of software documentation and
suggests separating documentation content into
four categories:
the abstract.
the application information,
the problem (or function) definition,
the programming information.
9
Application Information
The abstract's goal is to provide the user with
enough information to enable an easy decision
about whether the software is suitable for the
user's needs.
According to the standard, this information should
include specific functions of the software, the
required computer environment, and all the
materials available to the user in the software
package, including manuals.
10
Application Information
The application information describes:
The application information section summarized
the function of each major program option
the way the software handles files
the effect of data storage requirements on the
software
the range of values and variables that can be used
in the software
the control commands required to execute the
program
the nature of the output, including the way the
output relates to the input
the problems the software is designed to solve,
and specifies how to use the software, especially for
preparing input data and interpreting computed results.
This section should be concise enough to enable
effective use of the software and to serve as a
reference source for user questions.
It also includes a brief discussion of the comparative
strengths and weaknesses of the software in relation
to other competing or related software packages.
11
12
Header Block Comment
/***********************************************************
COMPONENT TO FIND INTERSECTION OF TWO LINES
Header Block Comment
COMPONENT NAME: FINDPT
PROGRAMMER: E. ELLIS
VERSION: 1.0 (First coded on: 2 FEBRUARY 2001/ Last modified on
22 August 2005)
The answers to the following questions should be
included in the header block comment:
What is the component is called?
Who wrote the component?
Where the component fits in the general system design?
When the component was written and revised?
Why the component exists?
How the component uses its data structures, algorithms
and control?
13
//**********************************************************
// PROGRAM SCAN: Program to scan a line of text for a given character
// PROGRAMMER: Beatrice Clarman (718) 345-6789/ bc@[Link]
// CALLING SEQUENCE: CALL SCAN(LENGTH,CHAR,NTEXT)
//
where LENGTH is the length of the line to be scanned;
//
CHAR is the character sought. Line of text is passed as array
//
NTEXT.
// VERSION 1: written 3 November 2000 by B. Clarman
// REVISION 1.1: 5 December 2001 by B Clarman to improve searching
//
algorithm.
// PURPOSE: General-purpose scanning module to be used for each new
//
line of text, no matter the length. One of several text utilities
//
designed to add a character to a line of text, read a character,
//
change a character or delete a character.
// DATA STRUCTURES: Variable LENGTH integer
//
Variable CHAR character
//
Array NTEXT character array of length LENGTH
// ALGORITHM: Read array NTEXT one character at a time; if CHAR is
//
found, position in NTEXT returned in variable LENGTH; else
//
variable LENGTH set to 0.
//**********************************************************
PROCEDURE INVOCATION:
CALL FINDPT ( A1, B1, C1, A2, B2, C2, XS, YS, FLAG )
INPUT PARAMETERS:
INPUT LINES ARE OF THE FORM
A1*X + B1*Y + C1 = 0 AND
A2*X + B2*Y + C2 = 0
SO INPUT IS COEFFICIENTS A1, B1, C1 AND A2, B2, C2
OUTPUT PARAMETERS:
IF LINES ARE PARALLEL, FLAG SET TO 1.
ELSE FLAG = 0 AND POINT OF INTERSECTION IS (XS, YS) 14
***********************************************************/
/*
RELATIONSHIP RANDOM GAME: Program that generates direct
relationships from indirect relationships.
PROGRAMMER: Mr. Jack Bean
TELEPHONE: (868) 640-0000
EMAIL: jbean@[Link]
VERSION 1: written 7 DEC 2005 by Mr. Jack Bean
REVISION 1.1: 5 JAN 2006 by Mr. Jack Bean to improve algorithm to
search for existing indirect relationship.
PURPOSE: Option in the game, in which the name of individual and
degree of indirect relationship is provided by user. Component
randomly generates indirect relationship, once it exists, and
requests a reply from user to guess the direct relationship and the
family members who fit this description.
15
16
Other Program Comments
FUNCTION CALL:
RANDOM_GAME(MEMBERS,NAME,DEGREE)
- MEMBERS is a list of all family members. It uses a list
container of data structures, which includes IndividualName,
Sex, MomName, DadName, SpouseName.
- NAME is the first and last names of the individual used to
whom the indirect relationship is referenced. It uses a data
structure consisting of two strings{Fname, Lname}.
- DEGREE of the "indirect" relationship is the number of
"direct"
relationships, using the allowed relationship
keywords such as: Mother, Father, Uncle, Aunt, Sister,
Brother, Cousin. This is an unsigned integer.
It is useless to write the following:
// Increment i3
i3 = i3 + 1;
More information is added in the following:
// Set counter to read next case
i3 = i3 + 1;
ALGORITHM:
Using NAME search for existence of INDIRECT
RELATIONSHIP; if INDIRECT RELATIONSHIP exists,
generate DIRECT RELATIONSHIP and select MEMBERS that
have this relationship; Request answer from user; Generate
response about correctness of answers.
17
*/
//find the arithmetic maximum of arg1 and arg2
int Math::Max( int arg1, int arg2 ) {
if ( arg1 > arg2 ) {
return arg1;
}
else {
return arg2;
}
}
//find the arithmetic minimum of arg1 and arg2
int Math::Min( int arg1, int arg2 ) {
if ( arg1 < arg2 ) {
return arg1;
}
else {
return arg2;
}
}
It is ideal for the variable name to explain the
activity. Hence comments may not be necessary.
This is shown in the following:
case_counter = case_counter +1;
18
Inline Comments
Reasons for commenting a line of code
are:
The single line is complicated enough to
need an explanation.
The single line once had an error and you
want a record of the error.
19
20
Meaningful Variable Names
Meaningful Variable Names
x = x - xx;
xxx = aretha + SalesTax( aretha );
x = x + LateFee( x1, x ) + xxx;
x = x + Interest( x1, x );
Is not as meaningful as:
balance = balance - lastPayment;
monthlyTotal = NewPurchases +SalesTax(
newPurchases );
balance = balance + LateFee( customerID, balance ) +
monthlyTotal;
balance = balance + Interest( customerID, balance );
21
Gorla, Benander, and Benander found that the
effort required to debug a program was
minimized when variables had names that
averaged 10 to 16 characters (1990).
Programs with names averaging 8 to 20
characters were almost as easy to debug.
The guideline doesnt mean that you should
try to make all of your variable names 9 to 15
or 10 to 16 characters long.
It does mean that if you look over your code
and see many names that are shorter, you
should check to be sure that the names are
as clear as they need to be.
22
Defensive Programming
Defensive Programming
Analogy:
In defensive driving, you adopt the mind-set that
youre never sure what the other drivers are going
to do.
That way, you make sure that if they do something
dangerous you wont be hurt.
You take responsibility for protecting yourself even
when it might be the other drivers fault.
In defensive programming, the main idea is
that if a routine is passed bad data, it wont be
hurt, even if the bad data is another routines
fault.
More generally, its the recognition that programs
will have problems and modifications, and that a
smart programmer will develop code accordingly.
23
A good program should use any of the following
guidelines:
garbage in, nothing out
garbage in, error message out
no garbage allowed in
Three general ways to handle garbage
Check the values of all data from external sources
Check the values of all routine input parameters
Decide how to handle bad inputs
24
Error handling techniques
Defensive Programming
Check the values of all data from external
sources
Ensure numeric values are within their tolerances
Ensure strings are valid for their intended purpose,
otherwise reject it
Check the values of all routine input
parameters
Substitute the next piece of valid data
Log a warning message to a file
Return an error code
Display an error message wherever the
error is encountered
Shutdown
Same as the above point except that data is
coming from internal routines
25
Substitute the next piece of
valid data
26
Log a warning message to a
file
When processing a stream of data,
some circumstances call for simply
returning the next valid data.
For example:
When bad data is detected, you might
choose to log a warning message to a
file and then continue on.
if youre taking readings from a
thermometer 100 times per second and
you dont get a valid reading one time, you
might simply wait another 1/100th of a
second and take the next reading.
27
This approach can be used in conjunction
with substituting the next piece of valid
data.
For example:
if youre reading records from a database
and encounter a corrupted record, you
might simply continue reading until you find
28
a valid record.
Return an error code
Error handling techniques
The specific mechanism for notifying the
rest of the system that an error has
occurred could be any of the following:
Display an error message wherever the error
is encountered
Set the value of a status variable
Return status as the functions return value
Throw an exception using the languages
built-in exception mechanism
29
This approach minimizes error-handling overhead
Shutdown
Some systems shut down whenever they detect
an error.
This approach is useful in safety critical
applications.
e.g. The software that controls radiation
equipment for treating cancer patients receives
bad input data for the radiation dosage. In this
case, shutting down is the best option.
30