Title: Software Construction How to create selfdocumenting code
1Software ConstructionHow to create
self-documenting code
www.mariocardinal.com
2Merci!
3What is software construction
4Why is software construction important
- Software construction is the central activity in
software development - Software construction is the only activity thats
guaranteed to happen on every project - Constructions artifact, the source code, is
often the only accurate description of the
software - Why not create self-documented code?
5The People Issue
- Fact 1 The most important factor in software
work is not the tools and techniques used by the
programmers but rather the quality of the
programmers themselves - Fact 2 The best programmers are up to 28 times
better than the worst programmers, according to
individual differences - Glass, Robert L., Facts and Fallacies of Software
Engineering, Boston, Addison-Wesley, 2003
6Difficulties about software constructionEssential
complexity
- Difficulties related to problem space
- Conformity
- Software must conform to the problem domain
rather than the other way around - Changeability
- Requirement and technology churn
- When the problem domain changes, the software
must change as well, and the problem domain
changes frequently - Transparency
- We have no visualization of executing programs
to guide us for our thinking - Non-continuous behavior
- No equivalent laws of physics
- Combinatorial explosion of state space
- More unlike parts are connected in myriads of
ways than any other system designed by human
beings
7Difficulties about software constructionAccidenta
l complexity
- Difficulties related to bad software construction
practices - Classes
- Routines
- Variables
- Statements
- Layout and style
8Focus on simplicity to manage complexity
- Minimize the amount of essential complexity that
anyones brain has to deal with at any one time - Architecture and design challenges
- Keep accidental complexity from proliferating
needlessly - Apply good software construction practices
(Classes, Routines, Variables, Statements, Layout
and style)
9Remove accidental complexity
- Good code is its own best documentation
for ( i 1 i lt num i ) meetsCriteria i
True for ( i 2 i lt num / 2 i )
j i i while ( j lt num )
meetsCriteria j False j j i
for ( i 1 i lt num i ) if (
meetsCriteria i ) Console.WriteLine (
i.ToString() " meets criteria." )
Coding Horror
10Using classes for managing complexity
- A key to being an effective programmer is
maximizing the portion of a program that you can
safely ignore while working on any one section of
code - Classes are the primary software construct for
accomplishing that objective
IDENTITY (Name Description) (Responsibilities
Collaborators)
BEHAVIOR (Message event)
STATE (Knowledge)
CLASS
11Classes Good abstraction
- Present a consistent level of abstraction in the
class contract - Be sure you understand what abstraction the class
is implementing - A class contract should hide something
- Consider abstraction and cohesion together
- Provide services in pairs with their opposites
- Make contract programmatic rather than semantic
- Avoid assumptions about how the contract will be
used that cannot be enforced by the compiler
12Routines Functional cohesion
- The single most important reason to create a
public routine in a class is to reduce complexity - Routine hides information and creates units of
functional cohesion - Routine must performs one and only one function
- Function that most benefits from being put into a
routine of its own is a simple one
13Routines Detailed design process
- Constructing routines using Unit Tests
Begin
Create a general design for the class
Design the routines
Review and test the class as a whole
Code the test of the routine
Code the routine
Done
14Using variables - Initialization
- Declare and initialize each variable close to
where its first used - Initialize each variable as its declared
int accountIndex 0 // code using
accountIndex ... double total 0.0 // code
using total ... boolean done false // code
using done while ( ! done ) ...
15Using variables One purpose
- Use each variable for one and only one purpose
- Avoid variables with hidden meanings
- Make sure that all declared variables are used
// Compute roots of a quadratic equation. // This
code assumes that (bb-4ac) is positive. temp
Sqrt( bb - 4ac ) root0 ( -b temp ) /
( 2 a ) root1 ( -b - temp ) / ( 2 a )
... // swap the roots temp root0 root0
root1 root1 temp
Coding Horror
16Variable name Readability
- Good variable names are a key element of program
readability - Code is read far more times than it is written
- Be sure that the names you choose favor read-time
convenience over write-time convenience - Names should be as specific as possible
- Names that are vague enough or general enough to
be used for more than one purpose are usually bad
names - Abbreviations are rarely needed with modern
programming languages
17Variable name Guidelines
- The most important consideration in naming a
variable is that the name fully and accurately
describe the entity the variable represents - An effective technique for coming up with a good
name is to state in words what the variable
represents - linePerPages
- Often that statement itself is the best variable
name - numberOfSeatsInTheStadium
18Variable name Loop indexes
- Think of a better name than i, j or k for loop
indexes variables
for ( teamIndex 0 teamIndex lt teamCount
teamIndex ) for ( eventIndex 0
eventIndex lt eventCount teamIndex
eventIndex ) score teamIndex
eventIndex 0
- If you modify a name with a qualifier like Index,
Count, Total, Sum, Average, Max, Min, Record or
String, put the modifier at the end of the name
19Variable name Boolean
- Give boolean variables names that imply True or
False - Use positive boolean variable names
- Boolean done
- Boolean error
- Boolean found
- Boolean succes
- Boolean ok
20Variable name Convention
- Regardless of the kind of project youre working
on, you should adopt a variable naming convention - Any convention at all is better than no
convention - The formality of the convention depends on the
size of your program and the number of people
working on it
21Variable name Sample convention
- ClassName Class names are in mixed upper and
lower case with an initial capital letter. - IInterfaceName Interface names are prefixed with
a I. - m_ClassVariable Member variables that are
available to multiple routines within a class,
but only within a class, are prefixed with an m_. - RoutineName() Routines are in mixed uppercase
and lowercase - _parameterVariable Parameter variables that are
available to a routine within a class, are
prefixed with an _. - localVariable Local variables are in mixed
uppercase and lowercase with an initial lower
case letter. The name should be independent of
the underlying data type and should refer to
whatever the variable represents. - CONSTANT Named constants are in ALL_CAPS.
22Statement Straight-line code
- Dependencies should be made obvious for
statements that must be in a specific order - Organize code
- Use of good routine names
- Use routine parameters
long expenseData InitializeExpenseData(
expenseData ) expenseData ComputeMarketingExpens
e( expenseData ) expenseData ComputeSalesExpense
( expenseData ) expenseData ComputeTravelExpense
( expenseData ) expenseData ComputePersonnelExpe
nse( expenseData ) DisplayExpenseSummary(
expenseData )
23Statement Straight-line code
- If code doesnt have order dependencies, keep
related statements as close together as possible - Makes code read from top to bottom
- Groups related statements
24Control statement Layout style
- Use pure block for control statement
A B C
D
A If (True) Then B C
D End If
if (true)
C
VB
25Control statement if statements
- Write the nominal path through the code first
then write the unusual cases - Put the normal case after the if rather than
after the else - Simplified complicated test with boolean function
calls - Make sure that you branch correctly
- Consider the else clause and test for correctness
- Replace if-then-else chains with other constructs
such as case statements
26Control statement case statements
- Choose the most effective ordering of cases
- Put the normal case first
- Order cases by frequency
- Order cases alphabetically or numerically
- Keep the actions of each case simple
- Dont make up phony variables in order to be able
to use the case statement - Use the default clause only to detect legitimate
defaults - Use the default clause in a case statement or the
last else in a chain of if-then-elses to trap
errors
27Control statement loop statements
- Keep loops simple helps readers of your code
- Treat the inside of the loop as it were a routine
- Dont make the reader look inside the loop to
understand the loop control - Think of a loop as a black box
While (!inpufile.EndOfFile()
moreDataAvailable)
28Commenting efficiently
- Ensure that comments describe things about the
code that the code cant say about itself at
the intent level - Use the pseudocode process to reduce commenting
time - Integrate commenting into your development style
- Avoid commenting styles that require a lot of
tedious clerical work - Use styles that dont break down or discourage
modification
29Programming style as Documentation
- Good code is its own best documentation
for ( i 1 i lt num i ) meetsCriteria i
True for ( i 2 i lt num / 2 i )
j i i while ( j lt num )
meetsCriteria j False j j i
for ( i 1 i lt num i ) if (
meetsCriteria i ) Console.WriteLine (
i.ToString() " meets criteria." )
Coding Horror
30Programming style as Documentation
- Good code is its own best documentation
// Initialize all numbers as prime for (
primeCandidate 1 primeCandidate lt num
primeCandidate ) isPrime primeCandidate
True // Find factorable numbers and set them
as non prime for ( int factor 2 factor lt ( num
/ 2 ) factor ) int factorableNumber
factor factor while ( factorableNumber lt num
) isPrime factorableNumber
False factorableNumber factorableNumber
factor // Display prime numbers for (
primeCandidate 1 primeCandidate lt num
primeCandidate ) if ( isPrime
primeCandidate ) Console.WriteLine (
primeCandidate.toString() " is prime." )