Code Complete ---- (Part 5 Statements)
======================================================================================
1. Organizing Straight-Line Code
Statements that must be in a speicific order
---- Organize code so that dependencies are obvious.
Statements whose order doesn't matter
---- Grouping related statements
DataA
OperateDataA;
.....
DataB
OperateDataB;
.....
======================================================================================
2. Using Conditions
IF-ELSE ...
--- Put the normal case after the 'if' rather than after the 'else'.
--- Consider teh else clause
---- Code the else clause or with a null statement with some comments
---- Simplify complicated tests with boolean function calls
---- Put the most common cases first
---- Make sure that all cases are covered
Code a final else clause with an error message or assertion to catch cases you didn't plan for.
Case
---- Choosing the most effective ordering of cases
--- order cases alphabetically or numerically
--- put the normal case first
--- Order cases by frequency
---- Use the default clause only to detect legitimate defaults, and to detect errors
======================================================================================
3. Controlling Loops
****When to Use Loop-With-Exit Loop****
score = 0;
GetNextRating(&ratingIncrement);
rating += ratingIncrement;
while(condition....){
GetNextScore(&scoreIncrement);
score += scoreIncrement;
GetNextRating(&ratingIncrement);
rating += ratingIncrement;
}

// Code Repeated and that isn't easy to maitain

score = 0;
while(true){
GetNextRating(&ratingIncrement);
rating += ratingIncrement;

if (!condition...)
break;

GetNextScore(&scoreIncrement);
score += scoreIncrement;
}

//Notice: Put all the exit conditions in one place
Don't monkey with the loop index of a for loop to make the loop terminate
---- when u set up a for loop, the loop counter is off limits, use a while loop to provide more control over the loop's exit conditions.
Avoid code that depends on the loop index's final value
int recordCount = 0;
for (; recordCount < MAX_RECORD; ++recordCount){
if (Entry[recordCount] == testValue)
break
//......

if (recordCount < MaxRECORD)
return true;
else
return false;
}

// It's easy to make an off-by-one error

{
bool found = false;
for (; recordCount < MAX_RECORD; ++recordCount){
if (Entry[recordCount] == testValue){
found = true;
break;
} //end if
} //end for

......

return false;
}
Consider using safety counters
safetyCounter = 0;

do {

node = node->Next;

...

safetyCounter++;

if ( safetyCounter >= SAFETY_LIMIT ) {

Assert( false, "Internal Error: Safety-Counter Violation." );

}

...

} while ( node->Next != NULL );
// for critical loops
Use 'continue' for tests at the top of a loop
======================================================================================
4. Unusual Control Structures
Mutilple Returns from a routine
Recursion
---- Make sure the recursion stops
---- Use safety counters to prevent infinite recursion
**--** Don't use recursion for factorials or Fibonacci numbers
int Factorial( int number ) {
if ( number == 1 ) {
return 1;
}
else {
return number * Factorial( number - 1 );
}
}

//

int Factorial( int number ) {
int intermediateResult = 1;
for ( int factor = 2; factor <= number; factor++ ) {
intermediateResult = intermediateResult * factor;
}
return intermediateResult;
}
======================================================================================
5. Table-Driven Methods
----- Direct Access Table
If ( month = 1 ) Then
days = 31
ElseIf ( month = 2 ) Then
days = 28
ElseIf ( month = 3 ) Then
days = 31
......

Dim daysPerMonth() As Integer = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
days = daysPerMonth( month-1 )


enum FieldType {
FieldType_FloatingPoint,
FieldType_Integer,
FieldType_String,
FieldType_TimeOfDay,
FieldType_Boolean,
FieldType_BitField,
FieldType_Last = FieldType_BitField
};

......

class AbstractField {
public:
virtual void ReadAndPrint( string, FileStatus & ) = 0;
}

class FloatingPointField : public AbstractField {
public:
virtual void ReadAndPrint( string, FileStatus & ) {
...
}
}
.....

AbstractField* field[ Field_Last ];

field[ Field_FloatingPoint ] = new FloatingPointField();
field[ Field_Integer ] = new IntegerField();
field[ Field_String ] = new StringField();
field[ Field_TimeOfDay ] = new TimeOfDayField();
field[ Field_Boolean ] = new BooleanField();
field[ Field_BitField ] = new BitFieldField();
.....

fieldIdx = 1;
while ( ( fieldIdx <= numFieldsInMessage ) and ( fileStatus == OK ) ) {
fieldType = fieldDescription[ fieldIdx ].FieldType;
fieldName = fieldDescription[ fieldIdx ].FieldName;
field[ fieldType ].ReadAndPrint( fieldName, fileStatus );
}

**** Fudging lookup keys ******
--- Transform the key to make it work directly
int KeyFromAge(){
return max( min( 66, age), 17 );
}
----- Indexed Access
Color Index
----- Stair-step access
Dim rangeLimit() As Double = { 50.0, 65.0, 75.0, 90.0, 100.0 }
Dim grade() As String = { "F", "D", "C", "B", "A" }
maxGradeLevel = grade.Length - 1
...

' assign a grade to a student based on the student's score
gradeLevel = 0
studentGrade = "A"

While ( ( studentGrade = "A" ) and ( gradeLevel < maxGradeLevel ) )
If ( studentScore < rangeLimit( gradeLevel ) ) Then
studentGrade = grade( gradeLevel )
End If
gradeLevel = gradeLevel + 1
Wend
Consider using a binary search rather than a sequential search
======================================================================================
6. General Control Issues
if (!statusOK) ---> if (errorDetected)
writing numeric expressions in number-line order
---- if ( MIN < i ) && ( i < MAX)
NULL Statements
--- Using DoNothing() to replace ';'. <#define or inline>
Taming dangerously deep nesting
======================================================================================
1. Organizing Straight-Line Code
Statements that must be in a speicific order
---- Organize code so that dependencies are obvious.
Statements whose order doesn't matter
---- Grouping related statements
DataA
OperateDataA;
.....
DataB
OperateDataB;
.....
======================================================================================
2. Using Conditions
IF-ELSE ...
--- Put the normal case after the 'if' rather than after the 'else'.
--- Consider teh else clause
---- Code the else clause or with a null statement with some comments
---- Simplify complicated tests with boolean function calls
---- Put the most common cases first
---- Make sure that all cases are covered
Code a final else clause with an error message or assertion to catch cases you didn't plan for.
Case
---- Choosing the most effective ordering of cases
--- order cases alphabetically or numerically
--- put the normal case first
--- Order cases by frequency
---- Use the default clause only to detect legitimate defaults, and to detect errors
======================================================================================
3. Controlling Loops
****When to Use Loop-With-Exit Loop****

























Don't monkey with the loop index of a for loop to make the loop terminate
---- when u set up a for loop, the loop counter is off limits, use a while loop to provide more control over the loop's exit conditions.
Avoid code that depends on the loop index's final value




//......























Consider using safety counters





















Use 'continue' for tests at the top of a loop
======================================================================================
4. Unusual Control Structures
Mutilple Returns from a routine
Recursion
---- Make sure the recursion stops
---- Use safety counters to prevent infinite recursion
**--** Don't use recursion for factorials or Fibonacci numbers



















======================================================================================
5. Table-Driven Methods
----- Direct Access Table



























































----- Indexed Access
Color Index
----- Stair-step access
















Consider using a binary search rather than a sequential search
======================================================================================
6. General Control Issues
if (!statusOK) ---> if (errorDetected)
writing numeric expressions in number-line order
---- if ( MIN < i ) && ( i < MAX)
NULL Statements
--- Using DoNothing() to replace ';'. <#define or inline>
Taming dangerously deep nesting