SlideShare a Scribd company logo
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Code Complete Series
Aecho
Penpower, Inc
aecho.liu@penpower.com.tw
2013, 06
1 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Overview
Overview
Organizing Straight Line Code
With Specific order
Statements whose order doesn’t matter
Using Conditionals
If statements
Case statements
Unusual Control Structures
Multiple returns from a routine
gotos
Taming Deep Nesting
2 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
References
Code Complete 2ed
• Ch 14, Organizing Straight Line Code
• Ch 15, Using Conditionals
• Ch 17, Unusual Control Structures
• Ch 19.4, Taming Deep Nesting
3 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Overview
Improve code qualities
• Readability
• Maintainability
4 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Organizing Straight Line Code
Statement order can be one of following categories
• must be a specific order
• order doesn’t matter
.
Sample of straight line codes
..
......
Foo () ;
HelloWorld () ;
f o r ( i n t i = 0; i < 100; i ++) {
H e l l o K i t t y ( ) ;
}
5 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
.
Run with specific order. The dependencies are obvious.
..
......
data = ReadData();
result = GetResultsFromData(data);
PrintResults(results);
6 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
.
Run with specific order. The dependencies are not obvious.
..
......
revenue.ComputeMonthly();
revenue.ComputeQuarterly();
revenue.ComputeAnnual();
7 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
Make the dependences obvious.
• Organize code
• Name routine
• Use routine parameters
• Document dependencies with comments
• Check dependencies with assertions or error-handling
8 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
.
With specific order, but not obviously.
..
......
ComputeMarketingExpense ()
ComputeSalesExpense ()
ComputeTravelExpense ()
ComputePersonnelExpense ()
DisplayExpenseSummary ()
• The ComputeMarketingExpense() will initialize the
expense.
• The dependencies are not obvious in above codes.
9 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
• The parameter expense gives a hint the following routines are
grouped.
• The names of InitialExpenseData() and
DisplayExpenseSummary() are obvious executed at first
and last.
.
Grouped with routine parameter
..
......
I n i t i a l E x p e n s e D a t a ( expense ) ;
ComputeMarketingExpense ( expense ) ;
ComputeSalesExpense ( expense ) ;
ComputeTravelExpense ( expense ) ;
ComputePersonalExpense ( expense ) ;
DisplayExpenseSummary ( expense ) ;
10 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
With specific order
.
Document dependencies with comments
..
......
/∗∗
∗ Compute expense data . Each of the r o u t i n e s a c c e s s e s
∗ the member data expenseData . DisplayExpenseSummary
∗ should be c a l l e d l a s t because i t depends on data
∗ c a l c u l a t e d by the other r o u t i n e s .
∗/
I n i t i a l E x p e n s e D a t a ( expense ) ;
ComputeMarketingExpense ( expense ) ;
ComputeSalesExpense ( expense ) ;
ComputeTravelExpense ( expense ) ;
ComputePersonalExpense ( expense ) ;
DisplayExpenseSummary ( expense ) ;
11 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Statements whose order doesn’t matter
• In the absence of routine dependencies, we can order
statement or block of code ...
• Keep related actions together.
• Grouping related statements.
• Ordering affects the readability, performance,
maintainability.
12 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Keep related actions together
.
The related actions are not together, but jump around
..
......
MarketingData marketingData ;
SalesData s a l e s D a t a ;
TravelData t r a v e l D a t a ;
t r a v e l D a t a . ComputeQuarterly () ;
s a l e s D a t a . ComputeQuarterly () ;
marketingData . ComputeQuarterly () ;
s a l e s D a t a . ComputeAnnual () ;
marketingData . ComputeAnnual () ;
t r a v e l D a t a . ComputeAnnual () ;
s a l e s D a t a . P r i n t () ;
t r a v e l D a t a . P r i n t () ;
marketingData . P r i n t () ;
13 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Keep related actions together
.
The related actions are together
..
......
MarketingData marketingData ;
marketingData . ComputeQuarterly () ;
marketingData . ComputeAnnual () ;
marketingData . P r i n t () ;
SalesData s a l e s D a t a ;
s a l e s D a t a . ComputeQuarterly () ;
s a l e s D a t a . ComputeAnnual () ;
s a l e s D a t a . P r i n t () ;
TravelData t r a v e l D a t a ;
t r a v e l D a t a . ComputeQuarterly () ;
t r a v e l D a t a . ComputeAnnual () ;
t r a v e l D a t a . P r i n t () ;
14 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Grouping related statements
15 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Grouping related statements
Bad grouped statements
16 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Grouping related statements
Bad grouped statements Well grouped statements
17 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Key points
• The strongest principle for organizing straight-line code is
ordering dependencies.
• Dependencies should be made obvious through the use of
good routine names, parameter lists, comments.
• If code doesn’t have order dependencies, keep related
statements as close together as possible.
18 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Using Conditionals
Using Conditionals:
• if statements
• case statements
19 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Guidelines for If statements
• Write the nominal path through the code first; then write the
unusual cases.
• Simplify complicated cases with boolean function calls.
• Put the common cases first.
• Make sure all cases are covered.
20 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Write the nominal path through the code first; then write the
unusual cases.
.
OpenFile ( i n p u t F i l e , s t a t u s ) ;
i f ( s t a t u s == S t a t u s E r r o r ) {
errorType = Fil eOpe nError ; // 1 , E r r o r Case
} e l s e {
ReadFile ( i n p u t F i l e , f i l e D a t a , s t a t u s ) ; // 2 , Normal Case
i f ( s t a t u s == S t a t u s S u c c e s s ) {
SummarizeFileData ( f i l e D a t a , summaryData , s t a t u s ) ; // 3 , Normal Case
i f ( s t a t u s == S t a t u s E r r o r ) {
errorType = ErrorTypeDataSummaryError ; // 4 , E r r o r Case
} e l s e {
PrintSummary ( summaryData ) ; // 5 , Normal case
SaveSummaryData ( summaryData , s t a t u s ) ;
i f ( s t a t u s == S t a t u s E r r o r ) {
errorType = SummarySaveError ; // 6 , E r r o r case
} e l s e {
UpdateAllCounts () ; // 7 , Normal case
EraseUndoFiles ( ) ;
errorType = ErrorTypeNone ;
}
}
} e l s e {
errorType = F i l e R e a d E r r o r ; //
}
}
21 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Write the nominal path through the code first; then write the
unusual cases.
.
OpenFile ( i n p u t F i l e , s t a t u s ) ;
i f ( s t a t u s == Status Suc cess ) {
ReadFile ( i n p u t F i l e , f i l e D a t a , s t a t u s ) ; // 1 , Normal Case
i f ( s t a t u s == S t a t u s S u c c e s s ) {
SummarizeFileData ( f i l e D a t a , summaryData , s t a t u s ) ; // 2 , Normal Case
i f ( s t a t u s == S t a t u s S u c c e s s ) {
PrintSummary ( summaryData ) ; // 3 , Normal case
SaveSummaryData ( summaryData , s t a t u s ) ;
i f ( s t a t u s == StatusSuccess ) {
UpdateAllCounts () ; // 4 , Normal case
EraseUndoFiles ( ) ;
errorType = ErrorTypeNone ;
} e l s e {
errorType = SummarySaveError ; // 5 , E r r o r case
}
} e l s e {
errorType = ErrorTypeDataSummaryError ; // 6 , E r r o r Case
}
} e l s e {
errorType = F i l e R e a d E r r o r ; // 7 , E r r o r Case
}
} e l s e {
errorType = Fil eOpe nError ; //
}
22 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
1. Error Case
2. Normal Case
3. Normal Case
4. Error Case
5. Normal Case
6. Error Case
7. Normal Case
1. Normal Case
2. Normal Case
3. Normal Case
4. Normal Case
5. Error Case
6. Error Case
7. Error Case
Easier to find the normal
path through the codes.
23 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Simplify complicated tests with boolean function calls
.
i f ( i n p u t C h a r a c t e r < SPACE ) {
characterType = CharacterType ControlCharacter ;
}
e l s e i f (
i n p u t C h a r a c t e r == ’ ’ | |
i n p u t C h a r a c t e r == ’ , ’ | |
i n p u t C h a r a c t e r == ’ . ’ | |
i n p u t C h a r a c t e r == ’ ! ’ | |
i n p u t C h a r a c t e r == ’ ( ’ | |
i n p u t C h a r a c t e r == ’ ) ’ | |
i n p u t C h a r a c t e r == ’ : ’ | |
i n p u t C h a r a c t e r == ’ ; ’ | |
i n p u t C h a r a c t e r == ’ ? ’ | |
i n p u t C h a r a c t e r == ’−’
){
characterType = CharacterType Punctuation ;
} e l s e i f ( ’ 0 ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’ 9 ’ ) {
characterType = C har a cterTyp e Dig it ;
} e l s e i f (
( ’ a ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’ z ’ ) | |
( ’A ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’Z ’ )
) {
characterType = C h a r a c t e r T y p e Le t t e r ;
}
24 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Simplify complicated tests with boolean function calls
.
With boolean function calls
..
......
i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) {
characterType = CharacterType ControlCharacter ;
}
e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) {
characterType = CharacterType Punctuation ;
}
e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) {
characterType = C har a cterTyp e Dig it ;
}
e l s e i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) {
characterType = C h a r a c t e r T y p e Le t t e r ;
}
25 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Put the most common cases first.
.
Most common case first
..
......
i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) {
// The most common case
characterType = C h a r a c t e r T y p e Le t t e r ;
}
e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) {
characterType = CharacterType Punctuation ;
}
e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) {
characterType = C har a cterTyp e Dig it ;
}
e l s e i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) {
// The l e a s t common case
characterType = CharacterType ControlCharacter ;
}
26 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
If statements
Use default case to trap errors.
.
Trap the errors with default case.
..
......
i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) {
characterType = C h a r a c t e r T y p e Le t t e r ;
}
e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) {
characterType = CharacterType Punctuation ;
}
e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) {
characterType = C har a cterTyp e Dig it ;
}
e l s e i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) {
characterType = CharacterType ControlCharacter ;
} e l s e {
// Trap the e r r o r s .
D i s p l a y I n t e r n a l E r r o r ( ” Unexpected type of c h a r a c t e r detected . ” ) ;
}
27 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Case Statements
Choosing the Most Effective Ordering of Cases
• Order cases alphabetically or numerically
If cases are equally important, putting them in A-B-C order to
improves readability.
• Put the normal case first
• Order cases by frequency
Put the most frequently executed cases first and the least
frequently executed last.
• Human readers can find the most common cases easily.
• Putting the common ones at the top of the code makes the
search quicker.
28 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Case statements
Tips of using case statements
• Keep the actions of each case simple.
Extract complicated codes to routine.
• Use the default clause to detect errors.
29 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Case statements
Tips of using case statements
• Keep the actions of each case simple.
Extract complicated codes to routine.
• Use the default clause to detect errors.
.
......
switch ( commandShortcutLetter ) {
case ’ a ’ :
PrintAnnualReport () ;
break ;
case ’ p ’ :
// no a c t i o n r e q u i r e d , but case was c o n s i d e r e d
break ;
case ’ q ’ :
P r i n t Q u a r t e r l y R e p o r t () ;
break ;
case ’ s ’ :
PrintSummaryReport () ;
break ;
d e f a u l t :
// Detect e r r o r s .
D i s p l a y I n t e r n a l E r r o r ( ” I n t e r n a l E r r o r 905: C a l l customer support . ” ) ;
}
30 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Case statements
• Generally, code that falls through one case to another is an
invitation to make mistake as the code is modified. It should
be avoided.
• Clearly and unmistakably identify the flow-through at the
end of case statement.
.
......
switch ( errorDocumentationLevel ) {
case DocumentationLevel Full :
D i s p l a y E r r o r D e t a i l s ( errorNumber ) ;
// FALLTHROUGH −− F u l l documentation a l s o p r i n t s summary comments
case DocumentationLevel Summary :
DisplayErrorSummary ( errorNumber ) ;
// FALLTHROUGH −− Summary documentation a l s o p r i n t s e r r o r number
case DocumentationLevel NumberOnly :
DisplayErrorNumber ( errorNumber ) ;
break ;
d e f a u l t :
D i s p l a y I n t e r n a l E r r o r ( ” I n t e r n a l E r r o r 905: C a l l customer support . ” ) ;
}
31 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Unusual Control Structure
• Multiple returns from a routine
• goto
32 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Multiple returns from a routine
Multiple returns from a routine.
• Use a return when it enhances readability.
• Use guard clauses1 to simplify the complex error processing.
1
Check invalid conditions and return error code directly.
33 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Multiple returns from a routine
.
Multiple returns from a routine
..
......
Comparison Compare ( i n t value1 , i n t value2 ) {
i f ( value1 < value2 ) {
r e t u r n Comparison LessThan ;
}
e l s e i f ( value1 > value2 ) {
r e t u r n Comparison GreaterThan ;
}
r e t u r n Comparison Equal ;
}
34 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Multiple returns from a routine
This codes can be re written with multiple returns...
.
Deep nesting
..
......
i f ( f i l e . validName () ) {
i f ( f i l e . Open () ) {
i f ( encryptionKey . v a l i d () ) {
i f ( f i l e . Decrypt ( encryptionKey ) {
// l o t s of statements
// . . .
}
}
}
}
35 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Multiple returns from a routine
.
Use guard clauses to clarify the nominal cases
..
......
i f ( ! f i l e . validName () ) r e t u r n ;
i f ( ! f i l e . open () ) r e t u r n ;
i f ( ! encryptionKey . v a l i d () ) r e t u r n ;
i f ( ! f i l e . Decrypt ( encryptionKey ) ) r e t u r n ;
// l o t s of statements
// . . .
36 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Multiple returns from a routine
.
More realistic codes. Use guard clauses to clarify the nominal
cases
..
......
i f ( ! f i l e . validName () ) r e t u r n F i l e E r r o r I n v a l i d N a m e ;
i f ( ! f i l e . open () ) r e t u r n F i l e E r r o r C a n t O p e n F i l e ;
i f ( ! encryptionKey . v a l i d () ) r e t u r n
F i l e E r r o r I n v a l i d E n c r y p t i o n K e y ;
i f ( ! f i l e . Decrypt ( encryptionKey ) ) r e t u r n
F i l e E r r o r C a n t D e c r y p t F i l e ;
// l o t s of statements
// . . .
37 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
gotos
About goto statements.
• Generally, Without goto → High quality codes
• Under some situations, goto → High readability and
maintainability.
38 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
gotos
.
Error processing and gotos
..
e r r o r S t a t e = F i l e S t a t u s S u c c e s s ;
f i l e I n d e x = 0;
w h i l e ( f i l e I n d e x < numFilesToPurge ) {
f i l e I n d e x += 1;
i f ( ! F i n d F i l e ( f i l e L i s t ( f i l e I n d e x ) , f i l e T o P u r g e ) ) {
e r r o r S t a t e = F i l e S t a t u s F i l e F i n d E r r o r ;
goto End Proc ;
}
i f ( ! OpenFile ( f i l e T o P u r g e ) ) {
e r r o r S t a t e = F i l e S t a t u s F i l e O p e n E r r o r ;
goto End Proc ;
}
i f ( ! O v e r w r i t e F i l e ( f i l e T o P u r g e ) ) {
e r r o r S t a t e = F i l e S t a t u s F i l e O v e r w r i t e E r r o r ;
goto End Proc ;
}
i f ( ! Erase ( f i l e T o P u r g e ) ){
e r r o r S t a t e = F i l e S t a t u s F i l e E r a s e E r r o r ;
goto End Proc ;
}
End Proc :
D e l e t e P u r g e F i l e L i s t ( f i l e L i s t , numFilesToPurge ) ; 39 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
• Few people can understand more than 3 level of nested if.
1986, Noam Chomsky, and Gerald Weinberg.
• Many researchers recommend avoiding nesting more than 3 or
4 levels.
Myers 1976, Marca 1981, and Ledgard and Tauer 1987a.
40 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
deep nesting if
..
......
i f ( i n p u t S t a t u s == I n p u t S t a t u s S u c c e s s ) {
// l o t s of code
. . .
i f ( p r i n t e r R o u t i n e != NULL ) {
// l o t s of code
. . .
i f ( SetupPage () ) {
// l o t s of code . . .
i f ( AllocMem ( &printData ) ) {
// l o t s of code
. . .
}
}
}
}
41 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Simplify a nested if by retesting part of the condition
..
i f ( i n p u t S t a t u s != I n p u t S t a t u s S u c c e s s )
goto EXIT ;
// l o t s of code
. . .
i f ( p r i n t e r R o u t i n e == NULL )
goto EXIT ;
// l o t s of code
. . .
i f ( ! SetupPage () )
goto EXIT ;
// l o t s of code
. . .
i f ( ! AllocMem ( &printData ) )
goto EXIT ;
// l o t s of code
. . .
EXIT :
r e t u r n ;
42 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Simplify a nested if by using a break block
..
do {
i f ( i n p u t S t a t u s != I n p u t S t a t u s S u c c e s s )
break ;
// l o t s of code
. . .
i f ( p r i n t e r R o u t i n e == NULL )
break ;
// l o t s of code
. . .
i f ( ! SetupPage () )
break ;
// l o t s of code
. . .
i f ( ! AllocMem ( &printData ) )
break ;
// l o t s of code
. . .
} w h i l e ( f a l s e ) ;
43 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Overgrown decision tree
..
......
i f ( 10 < q u a n t i t y ) {
i f ( 100 < q u a n t i t y ) {
i f ( 1000 < q u a n t i t y ) {
d i s c o u n t = 0 . 1 0 ;
}
e l s e {
d i s c o u n t = 0 . 0 5 ;
}
}
e l s e {
d i s c o u n t = 0 . 0 2 5 ;
}
}
e l s e {
d i s c o u n t = 0 . 0 ;
}
44 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Convert to a set by if-then-elses
..
......
i f ( 1000 < q u a n t i t y ) {
d i s c o u n t = 0 . 1 0 ;
}
e l s e i f ( 100 < q u a n t i t y ) {
d i s c o u n t = 0 . 0 5 ;
}
e l s e i f ( 10 < q u a n t i t y ) {
d i s c o u n t = 0 . 0 2 5 ;
}
e l s e {
d i s c o u n t = 0;
}
45 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Convert to a set by if-then-elses
..
......
i f ( 1000 < q u a n t i t y ) {
d i s c o u n t = 0 . 1 0 ;
}
e l s e i f ( ( 100 < q u a n t i t y ) && ( q u a n t i t y <= 1000 ) ) {
d i s c o u n t = 0 . 0 5 ;
}
e l s e i f ( ( 10 < q u a n t i t y ) && ( q u a n t i t y <= 100 ) ) {
d i s c o u n t = 0 . 0 2 5 ;
}
e l s e i f ( q u a n t i t y <= 10 ) {
d i s c o u n t = 0;
}
46 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
// p r o c e s s t r a n s a c t i o n depending on type of t r a n s a c t i o n
i f ( t r a n s a c t i o n . Type == TransactionType Deposit ) {
// p r o c e s s a d e p o s i t
i f ( t r a n s a c t i o n . AccountType == AccountType Checking ) {
i f ( t r a n s a c t i o n . AccountSubType == AccountSubType Business )
MakeBusinessCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountSubType == AccountSubType Personal )
MakePersonalCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountSubType == AccountSubType School )
MakeSchoolCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
}
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Savings )
MakeSavingsDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType DebitCard )
MakeDebitCardDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType MoneyMarket )
MakeMoneyMarketDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Cd )
MakeCDDep( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
}
e l s e i f ( t r a n s a c t i o n . Type == TransactionType Withdrawal ) {
// p r o c e s s a withdrawal
i f ( t r a n s a c t i o n . AccountType == AccountType Checking )
MakeCheckingWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Savings )
MakeSavingsWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
e l s e i f ( t r a n s a c t i o n . AccountType == AccountType DebitCard )
MakeDebitCardWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ;
} 47 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
.
Factor deeply nested code into its routine
..
// p r o c e s s t r a n s a c t i o n depending on type of t r a n s a c t i o n
i f ( t r a n s a c t i o n . Type == TransactionType Deposit ) {
ProcessDeposit (
t r a n s a c t i o n . AccountType ,
t r a n s a c t i o n . AccountSubType ,
t r a n s a c t i o n . AccountNum ,
t r a n s a c t i o n . Amount
) ;
}
e l s e i f ( t r a n s a c t i o n . Type == TransactionType Withdrawal ) {
ProcessWithdrawal (
t r a n s a c t i o n . AccountType ,
t r a n s a c t i o n . AccountNum ,
t r a n s a c t i o n . Amount
) ;
}
e l s e i f ( t r a n s a c t i o n . Type == TransactionType Transfer ) {
MakeFundsTransfer (
t r a n s a c t i o n . SourceAccountType ,
t r a n s a c t i o n . TargetAccountType ,
t r a n s a c t i o n . AccountNum ,
t r a n s a c t i o n . Amount ) ;
}
e l s e {
// p r o c e s s unknown t r a n s a c t i o n type
LogTransactionError ( ”Unknown Transaction Type” , t r a n s a c t i o n ) ;
} 48 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Taming Deep Nesting
Summary of Techniques for Reducing Deep Nesting
• Retest the part of condition.
• Convert to if-then-elses.
• Factor deeply nested code into its own routine.
• Use objects and polymorphic dispatch.
Design pattern. Ex, Strategy pattern, State pattern, ... etc.
• ... etc.
49 / 50
Overview
. . . . . .
. . . . .
Organizing Straight Line Code
. . . . . . . .
. . .
Using Conditionals
. . . .
. .
Unusual Control Structures Taming Deep Nesting
Ending
Any questions ?
50 / 50

More Related Content

PPTX
Ia prezantim
PPT
C tutorial
PPT
C Tutorials
PPT
Computation Chapter 4
PDF
Code tuning techniques
PPT
A Guideline to Test Your Own Code - Developer Testing
PDF
MOST_OpenFoundry_version control system_Git
PDF
Integration
Ia prezantim
C tutorial
C Tutorials
Computation Chapter 4
Code tuning techniques
A Guideline to Test Your Own Code - Developer Testing
MOST_OpenFoundry_version control system_Git
Integration

Viewers also liked (15)

PDF
Design in construction
PPTX
Java scriptcore brief introduction
PDF
程序员发展漫谈
PPTX
Variables
PPTX
程序员实践之路
PDF
Design in construction
PPT
代码大全(内训)
PDF
Defencive programming
PDF
高品質軟體的基本動作 101 + 102 for NUU
PDF
Code tuning strategies
PDF
高品質軟體的基本動作 101 for NTHU
PPT
Code Tuning
PDF
The pseudocode
PPT
Rm 1 Intro Types Research Process
Design in construction
Java scriptcore brief introduction
程序员发展漫谈
Variables
程序员实践之路
Design in construction
代码大全(内训)
Defencive programming
高品質軟體的基本動作 101 + 102 for NUU
Code tuning strategies
高品質軟體的基本動作 101 for NTHU
Code Tuning
The pseudocode
Rm 1 Intro Types Research Process
Ad

Similar to Coding Style (20)

PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PPTX
6. using control structures, conditional statements and loops
PDF
Solution Manual for Programming with Microsoft Visual Basic 2017 8th by Zak
PPT
Savitch ch 03
PPT
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PPT
Savitch Ch 03
PPT
Savitch Ch 03
PDF
Clean code and code smells
PDF
Starting Out with C From Control Structures through Objects 6th Edition Tony ...
PDF
Guidelines to clean coding
PDF
Coding Guidelines in CPP
PDF
Coding Guidelines - Crafting Clean Code
PPTX
12.6-12.9.pptx
PPT
Basic concept of c++
PDF
C++ How to Program 10th Edition Deitel Solutions Manual
PDF
Fortran 90 overview
PDF
Starting out with C from control structures through objects Eighth Edition To...
PDF
Programming
PPTX
lab-8 (1).pptx
C++ How to Program 10th Edition Deitel Solutions Manual
6. using control structures, conditional statements and loops
Solution Manual for Programming with Microsoft Visual Basic 2017 8th by Zak
Savitch ch 03
C++ How to Program 10th Edition Deitel Solutions Manual
Savitch Ch 03
Savitch Ch 03
Clean code and code smells
Starting Out with C From Control Structures through Objects 6th Edition Tony ...
Guidelines to clean coding
Coding Guidelines in CPP
Coding Guidelines - Crafting Clean Code
12.6-12.9.pptx
Basic concept of c++
C++ How to Program 10th Edition Deitel Solutions Manual
Fortran 90 overview
Starting out with C from control structures through objects Eighth Edition To...
Programming
lab-8 (1).pptx
Ad

More from Hung-Wei Liu (6)

PDF
2015q4_InnerCourse_Presentation
PDF
Optimistic Offline Locking
PDF
Dynamic Programming Languages
PPTX
Defensive Programming
PDF
2013 07 Transaction Isolation Level
PDF
2013 11 CSharp Tutorial Struct and Class
2015q4_InnerCourse_Presentation
Optimistic Offline Locking
Dynamic Programming Languages
Defensive Programming
2013 07 Transaction Isolation Level
2013 11 CSharp Tutorial Struct and Class

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
history of c programming in notes for students .pptx
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administraation Chapter 3
PDF
Digital Strategies for Manufacturing Companies
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Introduction to Artificial Intelligence
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Design an Analysis of Algorithms II-SECS-1021-03
2025 Textile ERP Trends: SAP, Odoo & Oracle
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Softaken Excel to vCard Converter Software.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
history of c programming in notes for students .pptx
Navsoft: AI-Powered Business Solutions & Custom Software Development
L1 - Introduction to python Backend.pptx
System and Network Administraation Chapter 3
Digital Strategies for Manufacturing Companies
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PTS Company Brochure 2025 (1).pdf.......
Introduction to Artificial Intelligence
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf

Coding Style

  • 1. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Code Complete Series Aecho Penpower, Inc [email protected] 2013, 06 1 / 50
  • 2. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Overview Overview Organizing Straight Line Code With Specific order Statements whose order doesn’t matter Using Conditionals If statements Case statements Unusual Control Structures Multiple returns from a routine gotos Taming Deep Nesting 2 / 50
  • 3. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting References Code Complete 2ed • Ch 14, Organizing Straight Line Code • Ch 15, Using Conditionals • Ch 17, Unusual Control Structures • Ch 19.4, Taming Deep Nesting 3 / 50
  • 4. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Overview Improve code qualities • Readability • Maintainability 4 / 50
  • 5. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Organizing Straight Line Code Statement order can be one of following categories • must be a specific order • order doesn’t matter . Sample of straight line codes .. ...... Foo () ; HelloWorld () ; f o r ( i n t i = 0; i < 100; i ++) { H e l l o K i t t y ( ) ; } 5 / 50
  • 6. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order . Run with specific order. The dependencies are obvious. .. ...... data = ReadData(); result = GetResultsFromData(data); PrintResults(results); 6 / 50
  • 7. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order . Run with specific order. The dependencies are not obvious. .. ...... revenue.ComputeMonthly(); revenue.ComputeQuarterly(); revenue.ComputeAnnual(); 7 / 50
  • 8. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order Make the dependences obvious. • Organize code • Name routine • Use routine parameters • Document dependencies with comments • Check dependencies with assertions or error-handling 8 / 50
  • 9. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order . With specific order, but not obviously. .. ...... ComputeMarketingExpense () ComputeSalesExpense () ComputeTravelExpense () ComputePersonnelExpense () DisplayExpenseSummary () • The ComputeMarketingExpense() will initialize the expense. • The dependencies are not obvious in above codes. 9 / 50
  • 10. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order • The parameter expense gives a hint the following routines are grouped. • The names of InitialExpenseData() and DisplayExpenseSummary() are obvious executed at first and last. . Grouped with routine parameter .. ...... I n i t i a l E x p e n s e D a t a ( expense ) ; ComputeMarketingExpense ( expense ) ; ComputeSalesExpense ( expense ) ; ComputeTravelExpense ( expense ) ; ComputePersonalExpense ( expense ) ; DisplayExpenseSummary ( expense ) ; 10 / 50
  • 11. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting With specific order . Document dependencies with comments .. ...... /∗∗ ∗ Compute expense data . Each of the r o u t i n e s a c c e s s e s ∗ the member data expenseData . DisplayExpenseSummary ∗ should be c a l l e d l a s t because i t depends on data ∗ c a l c u l a t e d by the other r o u t i n e s . ∗/ I n i t i a l E x p e n s e D a t a ( expense ) ; ComputeMarketingExpense ( expense ) ; ComputeSalesExpense ( expense ) ; ComputeTravelExpense ( expense ) ; ComputePersonalExpense ( expense ) ; DisplayExpenseSummary ( expense ) ; 11 / 50
  • 12. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Statements whose order doesn’t matter • In the absence of routine dependencies, we can order statement or block of code ... • Keep related actions together. • Grouping related statements. • Ordering affects the readability, performance, maintainability. 12 / 50
  • 13. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Keep related actions together . The related actions are not together, but jump around .. ...... MarketingData marketingData ; SalesData s a l e s D a t a ; TravelData t r a v e l D a t a ; t r a v e l D a t a . ComputeQuarterly () ; s a l e s D a t a . ComputeQuarterly () ; marketingData . ComputeQuarterly () ; s a l e s D a t a . ComputeAnnual () ; marketingData . ComputeAnnual () ; t r a v e l D a t a . ComputeAnnual () ; s a l e s D a t a . P r i n t () ; t r a v e l D a t a . P r i n t () ; marketingData . P r i n t () ; 13 / 50
  • 14. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Keep related actions together . The related actions are together .. ...... MarketingData marketingData ; marketingData . ComputeQuarterly () ; marketingData . ComputeAnnual () ; marketingData . P r i n t () ; SalesData s a l e s D a t a ; s a l e s D a t a . ComputeQuarterly () ; s a l e s D a t a . ComputeAnnual () ; s a l e s D a t a . P r i n t () ; TravelData t r a v e l D a t a ; t r a v e l D a t a . ComputeQuarterly () ; t r a v e l D a t a . ComputeAnnual () ; t r a v e l D a t a . P r i n t () ; 14 / 50
  • 15. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Grouping related statements 15 / 50
  • 16. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Grouping related statements Bad grouped statements 16 / 50
  • 17. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Grouping related statements Bad grouped statements Well grouped statements 17 / 50
  • 18. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Key points • The strongest principle for organizing straight-line code is ordering dependencies. • Dependencies should be made obvious through the use of good routine names, parameter lists, comments. • If code doesn’t have order dependencies, keep related statements as close together as possible. 18 / 50
  • 19. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Using Conditionals Using Conditionals: • if statements • case statements 19 / 50
  • 20. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Guidelines for If statements • Write the nominal path through the code first; then write the unusual cases. • Simplify complicated cases with boolean function calls. • Put the common cases first. • Make sure all cases are covered. 20 / 50
  • 21. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Write the nominal path through the code first; then write the unusual cases. . OpenFile ( i n p u t F i l e , s t a t u s ) ; i f ( s t a t u s == S t a t u s E r r o r ) { errorType = Fil eOpe nError ; // 1 , E r r o r Case } e l s e { ReadFile ( i n p u t F i l e , f i l e D a t a , s t a t u s ) ; // 2 , Normal Case i f ( s t a t u s == S t a t u s S u c c e s s ) { SummarizeFileData ( f i l e D a t a , summaryData , s t a t u s ) ; // 3 , Normal Case i f ( s t a t u s == S t a t u s E r r o r ) { errorType = ErrorTypeDataSummaryError ; // 4 , E r r o r Case } e l s e { PrintSummary ( summaryData ) ; // 5 , Normal case SaveSummaryData ( summaryData , s t a t u s ) ; i f ( s t a t u s == S t a t u s E r r o r ) { errorType = SummarySaveError ; // 6 , E r r o r case } e l s e { UpdateAllCounts () ; // 7 , Normal case EraseUndoFiles ( ) ; errorType = ErrorTypeNone ; } } } e l s e { errorType = F i l e R e a d E r r o r ; // } } 21 / 50
  • 22. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Write the nominal path through the code first; then write the unusual cases. . OpenFile ( i n p u t F i l e , s t a t u s ) ; i f ( s t a t u s == Status Suc cess ) { ReadFile ( i n p u t F i l e , f i l e D a t a , s t a t u s ) ; // 1 , Normal Case i f ( s t a t u s == S t a t u s S u c c e s s ) { SummarizeFileData ( f i l e D a t a , summaryData , s t a t u s ) ; // 2 , Normal Case i f ( s t a t u s == S t a t u s S u c c e s s ) { PrintSummary ( summaryData ) ; // 3 , Normal case SaveSummaryData ( summaryData , s t a t u s ) ; i f ( s t a t u s == StatusSuccess ) { UpdateAllCounts () ; // 4 , Normal case EraseUndoFiles ( ) ; errorType = ErrorTypeNone ; } e l s e { errorType = SummarySaveError ; // 5 , E r r o r case } } e l s e { errorType = ErrorTypeDataSummaryError ; // 6 , E r r o r Case } } e l s e { errorType = F i l e R e a d E r r o r ; // 7 , E r r o r Case } } e l s e { errorType = Fil eOpe nError ; // } 22 / 50
  • 23. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements 1. Error Case 2. Normal Case 3. Normal Case 4. Error Case 5. Normal Case 6. Error Case 7. Normal Case 1. Normal Case 2. Normal Case 3. Normal Case 4. Normal Case 5. Error Case 6. Error Case 7. Error Case Easier to find the normal path through the codes. 23 / 50
  • 24. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Simplify complicated tests with boolean function calls . i f ( i n p u t C h a r a c t e r < SPACE ) { characterType = CharacterType ControlCharacter ; } e l s e i f ( i n p u t C h a r a c t e r == ’ ’ | | i n p u t C h a r a c t e r == ’ , ’ | | i n p u t C h a r a c t e r == ’ . ’ | | i n p u t C h a r a c t e r == ’ ! ’ | | i n p u t C h a r a c t e r == ’ ( ’ | | i n p u t C h a r a c t e r == ’ ) ’ | | i n p u t C h a r a c t e r == ’ : ’ | | i n p u t C h a r a c t e r == ’ ; ’ | | i n p u t C h a r a c t e r == ’ ? ’ | | i n p u t C h a r a c t e r == ’−’ ){ characterType = CharacterType Punctuation ; } e l s e i f ( ’ 0 ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’ 9 ’ ) { characterType = C har a cterTyp e Dig it ; } e l s e i f ( ( ’ a ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’ z ’ ) | | ( ’A ’ <= i n p u t C h a r a c t e r && i n p u t C h a r a c t e r <= ’Z ’ ) ) { characterType = C h a r a c t e r T y p e Le t t e r ; } 24 / 50
  • 25. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Simplify complicated tests with boolean function calls . With boolean function calls .. ...... i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) { characterType = CharacterType ControlCharacter ; } e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) { characterType = CharacterType Punctuation ; } e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) { characterType = C har a cterTyp e Dig it ; } e l s e i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) { characterType = C h a r a c t e r T y p e Le t t e r ; } 25 / 50
  • 26. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Put the most common cases first. . Most common case first .. ...... i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) { // The most common case characterType = C h a r a c t e r T y p e Le t t e r ; } e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) { characterType = CharacterType Punctuation ; } e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) { characterType = C har a cterTyp e Dig it ; } e l s e i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) { // The l e a s t common case characterType = CharacterType ControlCharacter ; } 26 / 50
  • 27. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting If statements Use default case to trap errors. . Trap the errors with default case. .. ...... i f ( I s L e t t e r ( i n p u t C h a r a c t e r ) ) { characterType = C h a r a c t e r T y p e Le t t e r ; } e l s e i f ( I s P u n c t u a t i o n ( i n p u t C h a r a c t e r ) ) { characterType = CharacterType Punctuation ; } e l s e i f ( I s D i g i t ( i n p u t C h a r a c t e r ) ) { characterType = C har a cterTyp e Dig it ; } e l s e i f ( I s C o n t r o l ( i n p u t C h a r a c t e r ) ) { characterType = CharacterType ControlCharacter ; } e l s e { // Trap the e r r o r s . D i s p l a y I n t e r n a l E r r o r ( ” Unexpected type of c h a r a c t e r detected . ” ) ; } 27 / 50
  • 28. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Case Statements Choosing the Most Effective Ordering of Cases • Order cases alphabetically or numerically If cases are equally important, putting them in A-B-C order to improves readability. • Put the normal case first • Order cases by frequency Put the most frequently executed cases first and the least frequently executed last. • Human readers can find the most common cases easily. • Putting the common ones at the top of the code makes the search quicker. 28 / 50
  • 29. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Case statements Tips of using case statements • Keep the actions of each case simple. Extract complicated codes to routine. • Use the default clause to detect errors. 29 / 50
  • 30. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Case statements Tips of using case statements • Keep the actions of each case simple. Extract complicated codes to routine. • Use the default clause to detect errors. . ...... switch ( commandShortcutLetter ) { case ’ a ’ : PrintAnnualReport () ; break ; case ’ p ’ : // no a c t i o n r e q u i r e d , but case was c o n s i d e r e d break ; case ’ q ’ : P r i n t Q u a r t e r l y R e p o r t () ; break ; case ’ s ’ : PrintSummaryReport () ; break ; d e f a u l t : // Detect e r r o r s . D i s p l a y I n t e r n a l E r r o r ( ” I n t e r n a l E r r o r 905: C a l l customer support . ” ) ; } 30 / 50
  • 31. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Case statements • Generally, code that falls through one case to another is an invitation to make mistake as the code is modified. It should be avoided. • Clearly and unmistakably identify the flow-through at the end of case statement. . ...... switch ( errorDocumentationLevel ) { case DocumentationLevel Full : D i s p l a y E r r o r D e t a i l s ( errorNumber ) ; // FALLTHROUGH −− F u l l documentation a l s o p r i n t s summary comments case DocumentationLevel Summary : DisplayErrorSummary ( errorNumber ) ; // FALLTHROUGH −− Summary documentation a l s o p r i n t s e r r o r number case DocumentationLevel NumberOnly : DisplayErrorNumber ( errorNumber ) ; break ; d e f a u l t : D i s p l a y I n t e r n a l E r r o r ( ” I n t e r n a l E r r o r 905: C a l l customer support . ” ) ; } 31 / 50
  • 32. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Unusual Control Structure • Multiple returns from a routine • goto 32 / 50
  • 33. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Multiple returns from a routine Multiple returns from a routine. • Use a return when it enhances readability. • Use guard clauses1 to simplify the complex error processing. 1 Check invalid conditions and return error code directly. 33 / 50
  • 34. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Multiple returns from a routine . Multiple returns from a routine .. ...... Comparison Compare ( i n t value1 , i n t value2 ) { i f ( value1 < value2 ) { r e t u r n Comparison LessThan ; } e l s e i f ( value1 > value2 ) { r e t u r n Comparison GreaterThan ; } r e t u r n Comparison Equal ; } 34 / 50
  • 35. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Multiple returns from a routine This codes can be re written with multiple returns... . Deep nesting .. ...... i f ( f i l e . validName () ) { i f ( f i l e . Open () ) { i f ( encryptionKey . v a l i d () ) { i f ( f i l e . Decrypt ( encryptionKey ) { // l o t s of statements // . . . } } } } 35 / 50
  • 36. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Multiple returns from a routine . Use guard clauses to clarify the nominal cases .. ...... i f ( ! f i l e . validName () ) r e t u r n ; i f ( ! f i l e . open () ) r e t u r n ; i f ( ! encryptionKey . v a l i d () ) r e t u r n ; i f ( ! f i l e . Decrypt ( encryptionKey ) ) r e t u r n ; // l o t s of statements // . . . 36 / 50
  • 37. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Multiple returns from a routine . More realistic codes. Use guard clauses to clarify the nominal cases .. ...... i f ( ! f i l e . validName () ) r e t u r n F i l e E r r o r I n v a l i d N a m e ; i f ( ! f i l e . open () ) r e t u r n F i l e E r r o r C a n t O p e n F i l e ; i f ( ! encryptionKey . v a l i d () ) r e t u r n F i l e E r r o r I n v a l i d E n c r y p t i o n K e y ; i f ( ! f i l e . Decrypt ( encryptionKey ) ) r e t u r n F i l e E r r o r C a n t D e c r y p t F i l e ; // l o t s of statements // . . . 37 / 50
  • 38. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting gotos About goto statements. • Generally, Without goto → High quality codes • Under some situations, goto → High readability and maintainability. 38 / 50
  • 39. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting gotos . Error processing and gotos .. e r r o r S t a t e = F i l e S t a t u s S u c c e s s ; f i l e I n d e x = 0; w h i l e ( f i l e I n d e x < numFilesToPurge ) { f i l e I n d e x += 1; i f ( ! F i n d F i l e ( f i l e L i s t ( f i l e I n d e x ) , f i l e T o P u r g e ) ) { e r r o r S t a t e = F i l e S t a t u s F i l e F i n d E r r o r ; goto End Proc ; } i f ( ! OpenFile ( f i l e T o P u r g e ) ) { e r r o r S t a t e = F i l e S t a t u s F i l e O p e n E r r o r ; goto End Proc ; } i f ( ! O v e r w r i t e F i l e ( f i l e T o P u r g e ) ) { e r r o r S t a t e = F i l e S t a t u s F i l e O v e r w r i t e E r r o r ; goto End Proc ; } i f ( ! Erase ( f i l e T o P u r g e ) ){ e r r o r S t a t e = F i l e S t a t u s F i l e E r a s e E r r o r ; goto End Proc ; } End Proc : D e l e t e P u r g e F i l e L i s t ( f i l e L i s t , numFilesToPurge ) ; 39 / 50
  • 40. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting • Few people can understand more than 3 level of nested if. 1986, Noam Chomsky, and Gerald Weinberg. • Many researchers recommend avoiding nesting more than 3 or 4 levels. Myers 1976, Marca 1981, and Ledgard and Tauer 1987a. 40 / 50
  • 41. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . deep nesting if .. ...... i f ( i n p u t S t a t u s == I n p u t S t a t u s S u c c e s s ) { // l o t s of code . . . i f ( p r i n t e r R o u t i n e != NULL ) { // l o t s of code . . . i f ( SetupPage () ) { // l o t s of code . . . i f ( AllocMem ( &printData ) ) { // l o t s of code . . . } } } } 41 / 50
  • 42. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Simplify a nested if by retesting part of the condition .. i f ( i n p u t S t a t u s != I n p u t S t a t u s S u c c e s s ) goto EXIT ; // l o t s of code . . . i f ( p r i n t e r R o u t i n e == NULL ) goto EXIT ; // l o t s of code . . . i f ( ! SetupPage () ) goto EXIT ; // l o t s of code . . . i f ( ! AllocMem ( &printData ) ) goto EXIT ; // l o t s of code . . . EXIT : r e t u r n ; 42 / 50
  • 43. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Simplify a nested if by using a break block .. do { i f ( i n p u t S t a t u s != I n p u t S t a t u s S u c c e s s ) break ; // l o t s of code . . . i f ( p r i n t e r R o u t i n e == NULL ) break ; // l o t s of code . . . i f ( ! SetupPage () ) break ; // l o t s of code . . . i f ( ! AllocMem ( &printData ) ) break ; // l o t s of code . . . } w h i l e ( f a l s e ) ; 43 / 50
  • 44. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Overgrown decision tree .. ...... i f ( 10 < q u a n t i t y ) { i f ( 100 < q u a n t i t y ) { i f ( 1000 < q u a n t i t y ) { d i s c o u n t = 0 . 1 0 ; } e l s e { d i s c o u n t = 0 . 0 5 ; } } e l s e { d i s c o u n t = 0 . 0 2 5 ; } } e l s e { d i s c o u n t = 0 . 0 ; } 44 / 50
  • 45. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Convert to a set by if-then-elses .. ...... i f ( 1000 < q u a n t i t y ) { d i s c o u n t = 0 . 1 0 ; } e l s e i f ( 100 < q u a n t i t y ) { d i s c o u n t = 0 . 0 5 ; } e l s e i f ( 10 < q u a n t i t y ) { d i s c o u n t = 0 . 0 2 5 ; } e l s e { d i s c o u n t = 0; } 45 / 50
  • 46. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Convert to a set by if-then-elses .. ...... i f ( 1000 < q u a n t i t y ) { d i s c o u n t = 0 . 1 0 ; } e l s e i f ( ( 100 < q u a n t i t y ) && ( q u a n t i t y <= 1000 ) ) { d i s c o u n t = 0 . 0 5 ; } e l s e i f ( ( 10 < q u a n t i t y ) && ( q u a n t i t y <= 100 ) ) { d i s c o u n t = 0 . 0 2 5 ; } e l s e i f ( q u a n t i t y <= 10 ) { d i s c o u n t = 0; } 46 / 50
  • 47. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . // p r o c e s s t r a n s a c t i o n depending on type of t r a n s a c t i o n i f ( t r a n s a c t i o n . Type == TransactionType Deposit ) { // p r o c e s s a d e p o s i t i f ( t r a n s a c t i o n . AccountType == AccountType Checking ) { i f ( t r a n s a c t i o n . AccountSubType == AccountSubType Business ) MakeBusinessCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountSubType == AccountSubType Personal ) MakePersonalCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountSubType == AccountSubType School ) MakeSchoolCheckDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Savings ) MakeSavingsDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountType == AccountType DebitCard ) MakeDebitCardDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountType == AccountType MoneyMarket ) MakeMoneyMarketDep ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Cd ) MakeCDDep( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } e l s e i f ( t r a n s a c t i o n . Type == TransactionType Withdrawal ) { // p r o c e s s a withdrawal i f ( t r a n s a c t i o n . AccountType == AccountType Checking ) MakeCheckingWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountType == AccountType Savings ) MakeSavingsWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; e l s e i f ( t r a n s a c t i o n . AccountType == AccountType DebitCard ) MakeDebitCardWithdrawal ( t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } 47 / 50
  • 48. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting . Factor deeply nested code into its routine .. // p r o c e s s t r a n s a c t i o n depending on type of t r a n s a c t i o n i f ( t r a n s a c t i o n . Type == TransactionType Deposit ) { ProcessDeposit ( t r a n s a c t i o n . AccountType , t r a n s a c t i o n . AccountSubType , t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } e l s e i f ( t r a n s a c t i o n . Type == TransactionType Withdrawal ) { ProcessWithdrawal ( t r a n s a c t i o n . AccountType , t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } e l s e i f ( t r a n s a c t i o n . Type == TransactionType Transfer ) { MakeFundsTransfer ( t r a n s a c t i o n . SourceAccountType , t r a n s a c t i o n . TargetAccountType , t r a n s a c t i o n . AccountNum , t r a n s a c t i o n . Amount ) ; } e l s e { // p r o c e s s unknown t r a n s a c t i o n type LogTransactionError ( ”Unknown Transaction Type” , t r a n s a c t i o n ) ; } 48 / 50
  • 49. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Taming Deep Nesting Summary of Techniques for Reducing Deep Nesting • Retest the part of condition. • Convert to if-then-elses. • Factor deeply nested code into its own routine. • Use objects and polymorphic dispatch. Design pattern. Ex, Strategy pattern, State pattern, ... etc. • ... etc. 49 / 50
  • 50. Overview . . . . . . . . . . . Organizing Straight Line Code . . . . . . . . . . . Using Conditionals . . . . . . Unusual Control Structures Taming Deep Nesting Ending Any questions ? 50 / 50