Download presentation
Presentation is loading. Please wait.
Published byMorris Morton Modified over 9 years ago
1
Using Variables Chapter 10-11
2
Outline 2 Variable Initialization Scope Persistence Using Each Variable for Single Purpose Variable Names
3
Data Literacy Test 3 abstract data type array bitmap boolean variable b-tree character variable container class double precision elongated stream enumerated type floating point heap index integer linked list named constant 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 0.5: know what a term means but aren’t sure
4
Loose Interpretation 4 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
5
Variable Initialization Problem 5 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
6
Guidelines for Variable Initialization 6 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 ) {... }
7
Guidelines for Variable Initialization 7 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
8
Guidelines for Variable Initialization 8 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
9
Scope 9 Scope or visibility The extent to which the variable is known and can be referenced throughout the program Minimizing vs maximizing scope 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?
10
Localize References to Variables 10 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
11
Variable Span 11 a =0; b=0; c=0; b=a+1 b=b/c; 1 line between 1 st /2 nd references to b: span of 1 0 line between 2 nd /3 rd references to b: span of 0 Average span For b, (1+0)/2=0.5
12
Live Time 12 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.
13
Measuring Live Time 13 1 // initialize all variables 2 recordIndex = 0 ; 3 total = 0; 4 done = false; … 26 while (recordIndex<recordCount){ 27 … 28 recordIndex = recordIndex+1; … 64 while (!done) { … 69 if (total>projectedTotal) { 70done = true; recordIndex: 28-2+1 total: 69-3+1 done: 70-4+1 Average: 54
14
Measuring Live Time - cont 14 … 25 recordIndex = 0 ; 26 while (recordIndex<recordCount){ 27 … 28 recordIndex = recordIndex+1; … 62 total = 0 ; 63 done = false; 64 while (!done) { … 69 if (total>projectedTotal) { 70done = true; recordIndex: 28-25+1 total: 69-62+1 done: 70-63+1 Average: 7
15
Keep Variables ‘Live’ for a Short Time 15 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
16
What Do You Think? 16 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); … }
17
Guidelines for Minimizing Scope 17
18
Guidelines for Minimizing Scope 18 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
19
Guidelines for Minimizing Scope 19 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
20
Persistence 20 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
21
Avoiding Persistence Problem 21 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.
22
What Do You Think? 22 // 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;
23
Using Each Variable for Single Purpose 23 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
24
Using Each Variable for Single Purpose 24 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
25
What Do You Think ? 25 x = x –xx; xxx = fido + SalesTax(fido); x = x +LateFee(x1, x) + xxx; x = x + Interest(x1, x);
26
Kinds of Names to Avoid 26 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
27
Kinds of Names to Avoid - cont 27 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
28
Reading 28 The Power of Variable Names ‘Code Complete’ Chapter 11.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.