Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 09 – Part II Using Variables

Similar presentations


Presentation on theme: "Chapter 09 – Part II Using Variables"— Presentation transcript:

1 Chapter 09 – Part II Using Variables

2 Outline Variable Initialization Scope Persistence
Using Each Variable for Single Purpose Variable Names

3 Data Literacy Test literal local variables lookup table member data
33 Data Literacy Test abstract data type array bitmap boolean variable b-tree character variable container class double precision elongated stream enumerated type floating point literal local variables lookup table member data pointer private retroactive synapse referential integrity stack string structured variable tree typedef union value chain variant Total Score 1: familiar : know what a term means but aren’t sure 33

4 Loose Interpretation 0-14: beginning programmer
44 Loose Interpretation 0-14: beginning programmer 15-19: intermediate programmer, or An experienced programmer who has forgotten a lot 20-24: expert programmer 25-29: know more about data types than Steve Consider writing your own book 30-32: your are a pompous fraud Elongated stream, retroactive synapse, value chain don’t refer to data types 44

5 Variable Initialization Problem
55 Variable Initialization Problem A variable may contain an initial value that you do not expect it to contain Never been assigned a value Outdated: assigned a value at some point, but no longer valid Part of the variable assigned a value, part has not 55

6 Guidelines for Variable Initialization
66 Guidelines for Variable Initialization Initialize each variable as it is declared Inexpensive form of defensive programming Initialize each var close to where it’s first used Some languages (e.g., VB) do not support initializing variables as they are declared Principle of proximity: keep related action together Ideally, declare and define each variable close to where it’s first used int accountIndex = 0; // code using accountIndex … double total = 0.0; // code using total … boolean done = false; // code using done while ( ! done ) { ... } 66

7 Guidelines for Variable Initialization
77 Guidelines for Variable Initialization Use final or const when possible Pay attention to counters and accumulators Forget to reset before the next time it is used Initialize a class’s member data in constructor Check the need to re-initialization Used by a loop used many times Needs to be reset between calls Use the compiler setting that automatically initialize variables 77

8 Guidelines for Variable Initialization
88 Guidelines for Variable Initialization Take advantage of compiler’s warning messages Check input parameters for validity Use a memory access checker to check for bad pointers Initialize working memory to a known value at the beginning of your program 88

9 Scope Scope or visibility
99 Scope Scope or visibility The extent to which the variable is known and can be referenced throughout the program Maximizing scope Convenience, e.g., global variables Easier to write; Harder to understand/debug/modify Minimizing scope Keep variables as local as possible Intellectual manageability, Easier to read Code programs to read or write? 99

10 Localize References to Variables
Localize References to Variables The code between references to a variable is a ‘window of vulnerability’ New code might be added, inadvertently altering the variable Someone reading the code might forget the value the variable is supposed to contain Measure how close together the references are span 1010

11 Variable Span a =0; b=0; c=0; b=a+1; b=b/c;
Variable Span a =0; b=0; c=0; b=a+1; b=b/c; 1 line between 1st/2nd references to b: span of 1 0 line between 2nd/3rd references to b: span of 0 Average span For b, (1+0)/2=0.5 1111

12 Live Time Total # of statements over which a variable is live
Live Time Total # of statements over which a variable is live Life begins/ends at the first/last reference isn't affected by how many times the variable is used between the first and last times it's referenced. 1212

13 Measuring Live Time recordIndex: 28-2+1 total: 69-3+1 done: 70-4+1
Measuring Live Time 1 // initialize all variables 2 recordIndex = 0 ; 3 total = 0; 4 done = false; 26 while (recordIndex<recordCount){ recordIndex = recordIndex+1; 64 while (!done) { if (total>projectedTotal) { done = true; recordIndex: total: done: Average: 54 1313

14 Measuring Live Time - cont
Measuring Live Time - cont 25 recordIndex = 0 ; 26 while (recordIndex<recordCount){ recordIndex = recordIndex+1; 62 total = 0 ; 63 done = false; 64 while (!done) { if (total>projectedTotal) { done = true; recordIndex: total: done: Average: 7 1414

15 Keep Variables ‘Live’ for a Short Time
Keep Variables ‘Live’ for a Short Time Keep live time as short as possible: advantages Reduce the window of vulnerability Concentrate on a smaller section of code Reduce the chance of initialization errors Make the code more readable Easier for refactoring or splitting a large routine into smaller routines 1515

16 What Do You Think? 16161616 1616 void SummarizeData(…){ …
GetOldData( oldData, &numOldData); GetnewData(newData, &numNewData); totalOldData = sum(oldData, numOldData); totalNewData = sum(newData, numNewData); PrintOldDataSummary(oldData, totalOldData, numOldData); PrintNewDataSummary(newData, totalNewData, numNewData); SaveOldDataSummary(totalOldData, numOldData); SaveNewDataSummary(totalNewData, numNewData); } 1616

17 Guidelines for Minimizing Scope
Guidelines for Minimizing Scope 1717

18 Guidelines for Minimizing Scope
Guidelines for Minimizing Scope Group related statements, and, if necessary, break related statements into separate routines Don't assign a value to a variable until just before the value is used 1818

19 Guidelines for Minimizing Scope
Guidelines for Minimizing Scope Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop When modify the loop, remember to make corresponding modifications to the initialization Favor the smallest possible scope Local to a specific loop, local to a routine, private to a class, then protected, then package, Global only as last resort 1919

20 Persistence Some variables persist
Persistence Some variables persist For the life of a block of code or routine Variables inside a for loop As long as you allow them to Objects created with new persist until garbage collected For the life of a program Global variables Forever Variables include values in database Problem - If you assume that a variable has a longer persistence than it really does 2020

21 Avoiding Persistence Problem
Avoiding Persistence Problem Use debug code or assertions to check critical variables for reasonable values Set variables to unreasonable values when you are through with them Set a pointer to null after you delete it Write code that assumes data isn’t persistent Develop the habit of declaring and initializing all data right before it’s used Be suspicious if data is used without a nearby initialization. 2121

22 What Do You Think? // compute roots of a quadratic equation
What Do You Think? // compute roots of a quadratic equation // this code assumes that (b*b-4*a*c) is positive temp = sqrt (b*b-4*a*c); root[0] = (-b + temp) / (2*a); root[1] = (-b - temp) / (2*a); //swap the roots temp = root[0]; root[0] = root[1]; root[1] = temp; 2222

23 Using Each Variable for Single Purpose
Using Each Variable for Single Purpose Using the same variable for different purposes makes it seem as though they are related when they’re not! Use discriminant for the first temp Use oldRoot for the second temp 2323

24 Using Each Variable for Single Purpose
Using Each Variable for Single Purpose Avoid variables with hidden meanings - different values mean different things customerID: a customer number unless its value>=500,000, in which case subtracting 500,000 results in the number of a delinquent account Make sure all declared variables are used 2424

25 What Do You Think? x = x –xx; xxx = fido + SalesTax(fido);
What Do You Think? x = x –xx; xxx = fido + SalesTax(fido); x = x +LateFee(x1, x) + xxx; x = x + Interest(x1, x); 2525

26 Kinds of Names to Avoid Avoiding misleading names or abbreviations
Kinds of Names to Avoid Avoiding misleading names or abbreviations Avoid names with similar meanings recordNum/numRecords Avoid names that sound similar wrap/rap Avoid numerals in names Avoid misspelled words in names Don’t differentiate names solely by capitalization Avoid multiple natural languages check/cheque 2626

27 Kinds of Names to Avoid - cont
Kinds of Names to Avoid - cont Avoid the names of standard types, variables, and routines If if=then then then = else; else else = if; // PL/1 Avoid names containing hard-to-read chars (1, l, I), (0, O), (2, Z), (S, 5), ... Don’t use names that are totally unrelated to what the variables represent 2727

28 Reading The Power of Variable Names ‘Code Complete’ Chapter 11.
Reading The Power of Variable Names ‘Code Complete’ Chapter 11. 2828


Download ppt "Chapter 09 – Part II Using Variables"

Similar presentations


Ads by Google