Code Complete ---- (Note 5 Statements)

本文探讨了代码组织技巧,如直线路程的整理、条件语句的使用等,并介绍了循环控制的最佳实践,还讨论了不常见的控制结构及其注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 
= 312831303130313130313031 }
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.065.075.090.0100.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


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值