SlideShare a Scribd company logo
1 of 50
Download to read offline
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

Viewers also liked

Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
Java scriptcore brief introduction
Java scriptcore brief introductionJava scriptcore brief introduction
Java scriptcore brief introductionHorky Chen
 
程序员发展漫谈
程序员发展漫谈程序员发展漫谈
程序员发展漫谈Horky Chen
 
程序员实践之路
程序员实践之路程序员实践之路
程序员实践之路Horky Chen
 
Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)Horky Chen
 
Defencive programming
Defencive programmingDefencive programming
Defencive programmingAsha Sari
 
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUUSu Jan
 
Code tuning strategies
Code tuning strategiesCode tuning strategies
Code tuning strategiesAsha Sari
 
高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHUSu Jan
 
Code Tuning
Code TuningCode Tuning
Code Tuningbgtraghu
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocodeAsha Sari
 
Rm 1 Intro Types Research Process
Rm   1   Intro Types   Research ProcessRm   1   Intro Types   Research Process
Rm 1 Intro Types Research Processitsvineeth209
 

Viewers also liked (15)

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

Similar to Coding Style

[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary
[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary	[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary
[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary EnlightenmentProject
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...CODE BLUE
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareGagan Deep
 
Fundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسیFundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسیSaman Chitsazian
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
@RISK Unchained Webinar
@RISK Unchained Webinar@RISK Unchained Webinar
@RISK Unchained WebinarAndrew Sich
 
Zenoss Monitroing – zendmd Scripting Guide
Zenoss Monitroing – zendmd Scripting GuideZenoss Monitroing – zendmd Scripting Guide
Zenoss Monitroing – zendmd Scripting GuideVCP Muthukrishna
 
Optimistic Offline Locking
Optimistic Offline LockingOptimistic Offline Locking
Optimistic Offline LockingHung-Wei Liu
 
VZAgent_SOAP_Tutorial
VZAgent_SOAP_TutorialVZAgent_SOAP_Tutorial
VZAgent_SOAP_Tutorialtutorialsruby
 
VZAgent_SOAP_Tutorial
VZAgent_SOAP_TutorialVZAgent_SOAP_Tutorial
VZAgent_SOAP_Tutorialtutorialsruby
 
CAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming ConventionsCAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming ConventionsGerardo Renteria
 
Verilog Lecture2 thhts
Verilog Lecture2 thhtsVerilog Lecture2 thhts
Verilog Lecture2 thhtsBéo Tú
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987乐群 陈
 

Similar to Coding Style (20)

[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary
[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary	[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary
[E-Dev-Day 2014][5/16] C++ and JavaScript bindings for EFL and Elementary
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
Data day2017
Data day2017Data day2017
Data day2017
 
Fundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسیFundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسی
 
Coding style for good synthesis
Coding style for good synthesisCoding style for good synthesis
Coding style for good synthesis
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
@RISK Unchained Webinar
@RISK Unchained Webinar@RISK Unchained Webinar
@RISK Unchained Webinar
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Web_Alg_Project
Web_Alg_ProjectWeb_Alg_Project
Web_Alg_Project
 
Zenoss Monitroing – zendmd Scripting Guide
Zenoss Monitroing – zendmd Scripting GuideZenoss Monitroing – zendmd Scripting Guide
Zenoss Monitroing – zendmd Scripting Guide
 
Optimistic Offline Locking
Optimistic Offline LockingOptimistic Offline Locking
Optimistic Offline Locking
 
C compiler(final)
C compiler(final)C compiler(final)
C compiler(final)
 
VZAgent_SOAP_Tutorial
VZAgent_SOAP_TutorialVZAgent_SOAP_Tutorial
VZAgent_SOAP_Tutorial
 
VZAgent_SOAP_Tutorial
VZAgent_SOAP_TutorialVZAgent_SOAP_Tutorial
VZAgent_SOAP_Tutorial
 
CAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming ConventionsCAL PROGRAMMING GUIDE Programming Conventions
CAL PROGRAMMING GUIDE Programming Conventions
 
Verilog Lecture2 thhts
Verilog Lecture2 thhtsVerilog Lecture2 thhts
Verilog Lecture2 thhts
 
Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987Compiler2016 by abcdabcd987
Compiler2016 by abcdabcd987
 
Parallel sysplex
Parallel sysplexParallel sysplex
Parallel sysplex
 

Recently uploaded

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

Coding Style

  • 1. 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
  • 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